List in Python

List is the collection of items which are ordered and changable. Items in the list can be of different data types. And list also allow duplicates items. It can be written as the comma separated values with in square brackets.

For Example :-

my_list = [23, 45, 'age', 34.34, 'hello']

Features of list:--

  1. The element of the list can be changed i.e list are mutable
  2. Lists are ordered.
  3. Element of list can be accessed by index
  4. All the elements of list can be of different data types
>>> my_list = [23, 45, 56, 67.89, 78]
>>> print(my_list)
[23, 45, 56, 67.89, 78]
>>> print(my_list[1])
45
>>> 

Basic List Operations:--

1. Length of list

>>> print('length of my_list ', len(my_list))
length of my_list  5
>>>

2. Concatenation of list

>>> list1 = [23, 45, 'rahul']
>>> list2 = [90, 'singh', 34.89, 'apple']
>>> list3 = list1 + list2
>>> print('Concatenation of list1 and list2 is ', list3)
Concatenation of list1 and list2 is  [23, 45, 'rahul', 90, 'singh', 34.89, 'apple']
>>> 

3. append(): It is used to add elment to the list at last position

>>> list1 = [23, 45, 'rahul']
>>> list1.append(45.89)
>>> print('Output:-- ' , list1)
Output:--  [23, 45, 'rahul', 45.89]
>>> 

4. insert(): It is used to add element to the list at specified position. Syntax my_list.insert(index, element).

>>> list1 = [23, 45, 'rahul']
>>> list1.insert(2, 'Banana')
>>> print('Output:-- ', list1)
Output:--  [23, 45, 'Banana', 'rahul']
>>> 

5. extend(): Adds contents of one list to the end of other list

>>> list1 = [23, 45, 'rahul']
>>> list2 = [56, 21, 90, 'abc']
>>> list1.extend(list2)
>>> print('Output:-  ', list1)
Output:-   [23, 45, 'rahul', 56, 21, 90, 'abc']
>>> 

6. sum() : Calculates sum of all the elements of List.

>>> list1 = [23, 34, 12, 34]
>>> sum_of_list1 = sum(list1)
>>> print('Sum of list1 is:- ', sum_of_list1)
Sum of list1 is:-  103
>>> 

7. count(): It is used to find out total occurrence of given element of List.

>>> list1 = [23, 45, 23, 78, 23, 76, 90]
>>> print('Total occurrence of 23 is ', list1.count(23))
Total occurance of 23 is  3
>>> 

8. min() : Calculates minimum of all the elements of List.

>>> list1 = [23, 45, 23, 78, 23, 76, 90]
>>> print('Minimum from list ', min(list1))
Minimum from list  23
>>> 

9. max(): Calculates maximum of all the elements of List

>>> list1 = [23, 45, 23, 78, 23, 76, 90]
>>> print('Maximum from list ', max(list1))
Maximum from list  90
>>> 

10. remove(): Used to delete mentioned element from list.

>>> list1 = [23, 45, 23, 78, 23, 76, 90]
>>> list1.remove(23)
>>> print('List after delete 23 from list ', list1)
List after delete 23 from list  [45, 23, 78, 23, 76, 90]
>>> 

 

Total Views: 488