Ticker

6/recent/ticker-posts

Python: List Data Structure

If we want to represent a group of individual objects as a single entity where insertion order preserved and duplicates are allowed, then we should go for List.

  • insertion order preserved.
  • duplicate objects are allowed
  • heterogeneous objects are allowed.

List is dynamic because based on our requirement we can increase the size and decrease the size.

In List the elements will be placed within square brackets and with a comma separator.

We can differentiate duplicate elements by using index and we can preserve insertion order by using index. Hence index will play very important role.

Python supports both positive and negative indexes. +ve index means from left to right where as negative index means right to left

[10,"A","B",20, 30, 10]


List objects are mutable.i.e we can change the content.

Creation of List Objects:

1. We can create empty list object as follows...

1) list=[] 
2) print(list) 
3) print(type(list)) 
4) 
5) [] 
6) <class 'list'> 

2. If we know elements already then we can create list as follows

list=[10,20,30,40]

3. With dynamic input:

1) list=eval(input("Enter List:")) 
2) print(list) 
3) print(type(list)) 
4) 
5) D:\Python_classes>py test.py 
6) Enter List:[10,20,30,40] 
7) [10, 20, 30, 40] 
8) <class 'list'> 
List Data Structure

4. With list() function:

1) l=list(range(0,10,2)) 
2) print(l) 
3) print(type(l)) 
4) 
5) D:\Python_classes>py test.py 
6) [0, 2, 4, 6, 8] 
7) <class 'list'> 
Eg:
1) s="durga" 
2) l=list(s) 
3) print(l) 
4) 
5) D:\Python_classes>py test.py 
6) ['d', 'u', 'r', 'g', 'a'] 

5. with split() function:

1) s="Learning Python is very very easy !!!" 
2) l=s.split() 
3) print(l) 
4) print(type(l)) 
5) 
6) D:\Python_classes>py test.py 
7) ['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!'] 
8) <class 'list'> 

Accessing elements of List:

We can access elements of the list either by using index or by using slice operator(:)

1. By using index:

List follows zero based index. ie index of first element is zero.
List supports both +ve and -ve indexes.
+ve index meant for Left to Right
-ve index meant for Right to Left

list=[10,20,30,40] 

List Data Structure

print(list[0]) ==>10
print(list[-1]) ==>40
print(list[10]) ==>IndexError: list index out of range

2. By using slice operator:

Syntax:

list2 = list1[start:stop:step]
start => it indicates the index where slice has to start
 default value is 0
stop =>It indicates the index where slice has to end
 default value is max allowed index of list ie length of the list
step =>increment value
 default value is 1

Eg:

1) n=[1,2,3,4,5,6,7,8,9,10] 
2) print(n[2:7:2]) 
3) print(n[4::2]) 
4) print(n[3:7]) 
5) print(n[8:2:-2]) 
6) print(n[4:100])
7) 
8) Output
9) D:\Python_classes>py test.py 
10) [3, 5, 7] 
11) [5, 7, 9] 
12) [4, 5, 6, 7] 
13) [9, 7, 5] 
14) [5, 6, 7, 8, 9, 10] 

List vs mutability:

Once we creates a List object,we can modify its content. Hence List objects are mutable.

Eg:

1) n=[10,20,30,40] 
2) print(n) 
3) n[1]=777 
4) print(n) 
5) 
6) D:\Python_classes>py test.py 
7) [10, 20, 30, 40] 
8) [10, 777, 30, 40]

Traversing the elements of List:

The sequential access of each element in the list is called traversal.

1. By using while loop:

1) n=[0,1,2,3,4,5,6,7,8,9,10] 
2) i=0 
3) while i<len(n): 
4) print(n[i]) 
5) i=i+1 
6) 
7) D:\Python_classes>py test.py 
8) 0 
9) 1 
10) 2 
11) 3 
12) 4 
13) 5 
14) 6 
15) 7 
16) 8 
17) 9
18) 10

2. To display elements by index wise:

1) l=["A","B","C"] 
2) x=len(l) 
3) for i in range(x): 
4) print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x) 
5) 
6) Output
7) D:\Python_classes>py test.py 
8) A is available at positive index: 0 and at negative index: -3 
9) B is available at positive index: 1 and at negative index: -2 
10) C is available at positive index: 2 and at negative index: -1 

Important functions of List:

I. To get information about list:

1. len():

 returns the number of elements present in the list

Eg: n=[10,20,30,40]
 print(len(n))==>4

2. count():

 It returns the number of occurrences of specified item in the list

1) n=[1,2,2,2,2,3,3] 
2) print(n.count(1)) 
3) print(n.count(2)) 
4) print(n.count(3)) 
5) print(n.count(4)) 
6) 
7) Output
8) D:\Python_classes>py test.py 
9) 1 
10) 4 
11) 2 
12) 0 

3. index() function:

returns the index of first occurrence of the specified item.

Eg:

1) n=[1,2,2,2,2,3,3] 
2) print(n.index(1)) ==>0 
3) print(n.index(2)) ==>1 
4) print(n.index(3)) ==>5 
5) print(n.index(4)) ==>ValueError: 4 is not in list 

II. Manipulating elements of List:

1. append() function:

We can use append() function to add item at the end of the list.

Eg:

1) list=[] 
2) list.append("A") 
3) list.append("B") 
4) list.append("C") 
5) print(list) 
6) 
7) D:\Python_classes>py test.py 
8) ['A', 'B', 'C'] 

Eg: To add all elements to list upto 100 which are divisible by 10

1) list=[] 
2) for i in range(101): 
3) if i%10==0: 
4) list.append(i) 
5) print(list) 
6) 
7) 
8) D:\Python_classes>py test.py 
9) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 

2. insert() function:

To insert item at specified index position

1) n=[1,2,3,4,5] 
2) n.insert(1,888) 
3) print(n) 
4) 
5) D:\Python_classes>py test.py 
6) [1, 888, 2, 3, 4, 5] 

Eg:

1) n=[1,2,3,4,5] 
2) n.insert(10,777) 
3) n.insert(-10,999) 
4) print(n) 
5) 
6) D:\Python_classes>py test.py 
7) [999, 1, 2, 3, 4, 5, 777]

Differences between append() and insert()

append() 
insert() 
In List when we add any element it will come in last i.e. it will be last element. In List we can insert any element in particular index number 

3. extend() function:

To add all items of one list to another list

l1.extend(l2) 
 all items present in l2 will be added to l1

Eg:

1) order1=["Chicken","Mutton","Fish"] 
2) order2=["RC","KF","FO"] 
3) order1.extend(order2) 
4) print(order1) 
5) 
6) D:\Python_classes>py test.py 
7) ['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

4. remove() function:

We can use this function to remove specified item from the list.If the item present multiple times then only first occurrence will be removed.

Eg:

1) n=[10,20,10,30] 
2) n.remove(10) 
3) print(n) 
4) 
5) D:\Python_classes>py test.py 
6) [20, 10, 30] 

5. pop() function:

It removes and returns the last element of the list.

This is only function which manipulates list and returns some element.

Eg:

1) n=[10,20,30,40] 
2) print(n.pop()) 
3) print(n.pop()) 
4) print(n) 
5) 
6) D:\Python_classes>py test.py 
7) 40 
8) 30 
9) [10, 20]

If the list is empty then pop() function raises IndexError

Differences between remove() and pop()

remove() 
pop() 
 1) We can use to remove special element from the List.  1) We can use to remove last element from the List. 
 2) It can’t return any value.  2) It returned removed element. 
 3) If special element not available then we get VALUE ERROR.  3) If List is empty then we get Error. 

III. Ordering elements of List:

1. reverse():

 We can use to reverse() order of elements of list.

1) n=[10,20,30,40] 
2) n.reverse() 
3) print(n) 
4) 
5) D:\Python_classes>py test.py 
6) [40, 30, 20, 10] 

2. sort() function:

In list by default insertion order is preserved. If want to sort the elements of list according to default natural sorting order then we should go for sort() method.

For numbers ==>default natural sorting order is Ascending Order

For Strings ==> default natural sorting order is Alphabetical Order

1) n=[20,5,15,10,0] 
2) n.sort() 
3) print(n) #[0,5,10,15,20] 
4) 
5) s=["Dog","Banana","Cat","Apple"] 
6) s.sort() 
7) print(s) #['Apple','Banana','Cat','Dog'] 

To sort in reverse of default natural sorting order:

We can sort according to reverse of default natural sorting order by using reverse=True argument.

Eg:

1. n=[40,10,30,20] 
2. n.sort() 
3. print(n) ==>[10,20,30,40] 
4. n.sort(reverse=True) 
5. print(n) ===>[40,30,20,10] 
6. n.sort(reverse=False) 
7. print(n) ==>[10,20,30,40] 

Aliasing and Cloning of List objects:

The process of giving another reference variable to the existing list is called aliasing.

Eg:

1) x=[10,20,30,40] 
2) y=x 
3) print(id(x)) 
4) print(id(y)) 

The problem in this approach is by using one reference variable if we are changing content,then those changes will be reflected to the other reference variable.

1) x=[10,20,30,40] 
2) y=x 
3) y[1]=777 
4) print(x) ==>[10,777,30,40] 

To overcome this problem we should go for cloning.

The process of creating exactly duplicate independent object is called cloning.

We can implement cloning by using slice operator or by using copy() function

1. By using slice operator:

1) x=[10,20,30,40] 
2) y=x[:] 
3) y[1]=777 
4) print(x) ==>[10,20,30,40] 
5) print(y) ==>[10,777,30,40] 

2. By using copy() function:

1) x=[10,20,30,40] 
2) y=x.copy() 
3) y[1]=777 
4) print(x) ==>[10,20,30,40] 
5) print(y) ==>[10,777,30,40] 

Using Mathematical operators for List Objects:

We can use + and * operators for List objects.

1. Concatenation operator(+):

We can use + to concatenate 2 lists into a single list

1) a=[10,20,30] 
2) b=[40,50,60] 
3) c=a+b 
4) print(c) ==>[10,20,30,40,50,60] 

2. Repetition Operator(*):

We can use repetition operator * to repeat elements of list specified number of times

Eg:

1) x=[10,20,30] 
2) y=x*3 
3) print(y)==>[10,20,30,10,20,30,10,20,30] 

Comparing List objects

We can use comparison operators for List objects.

Eg:

1. x=["Dog","Cat","Rat"] 
2. y=["Dog","Cat","Rat"] 
3. z=["DOG","CAT","RAT"] 
4. print(x==y) True 
5. print(x==z) False 
6. print(x != z) True 

Membership operators:

We can check whether element is a member of the list or not by using memebership operators.

in operator
not in operator

Eg:

1. n=[10,20,30,40] 
2. print (10 in n) 
3. print (10 not in n) 
4. print (50 in n) 
5. print (50 not in n) 
6. 
7. Output
8. True 
9. False 
10. False 
11. True

clear() function:

We can use clear() function to remove all elements of List.

Eg:

1. n=[10,20,30,40] 
2. print(n) 
3. n.clear() 
4. print(n) 
5. 
6. Output
7. D:\Python_classes>py test.py 
8. [10, 20, 30, 40] 
9. [] 

Nested Lists:

Sometimes we can take one list inside another list. Such type of lists are called nested lists.

Eg:

1. n=[10,20,[30,40]] 
2. print(n) 
3. print(n[0]) 
4. print(n[2]) 
5. print(n[2][0]) 
6. print(n[2][1]) 
7. 
8. Output
9. D:\Python_classes>py test.py 
10. [10, 20, [30, 40]] 
11. 10 
12. [30, 40] 
13. 30 
14. 40

Nested List as Matrix:

In Python we can represent matrix by using nested lists.

1) n=[[10,20,30],[40,50,60],[70,80,90]] 
2) print(n) 
3) print("Elements by Row wise:") 
4) for r in n: 
5) print(r) 
6) print("Elements by Matrix style:") 
7) for i in range(len(n)): 
8) for j in range(len(n[i])): 
9) print(n[i][j],end=' ') 
10) print() 
11) 
12) Output
13) D:\Python_classes>py test.py 
14) [[10, 20, 30], [40, 50, 60], [70, 80, 90]] 
15) Elements by Row wise: 
16) [10, 20, 30] 
17) [40, 50, 60] 
18) [70, 80, 90] 
19) Elements by Matrix style: 
20) 10 20 30 
21) 40 50 60 
22) 70 80 90 

List Comprehensions:

It is very easy and compact way of creating list objects from any iterable objects(like list,tuple,dictionary,range etc) based on some condition.

Syntax:

list=[expression for item in list if condition]

Eg:

1) s=[ x*x for x in range(1,11)] 
2) print(s) 
3) v=[2**x for x in range(1,6)] 
4) print(v) 
5) m=[x for x in s if x%2==0] 
6) print(m) 
7) 
8) Output
9) D:\Python_classes>py test.py 
10) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 
11) [2, 4, 8, 16, 32] 
12) [4, 16, 36, 64, 100] 

"Python List Data Structure"

"Python List Data Structure Implementation"

"The Indexing In Python 'List' Data Structure Starts From 0"

"Explain The Usage Of Python List Data Structure With Example"

"Python Sorted List Data Structure"

"Linked List Data Structure In Python"

"Doubly Linked List In Data Structure In Python"

"Python Linked List Data Structure"

"Python Program To Implement Stack Using List Data Structure"

"Python Index 'List' Data Structure From 0"