Indexing in Lists
L = [ 21, 45, 78, 92, 104]
+ve index | 0 | 1 | 2 | 3 | 4 |
Elements | 21 | 45 | 78 | 92 | 104 |
-ve index | -5 | -4 | -3 | -2 | -1 |
Forward indexing And Backward indexing
L = [21, 45, 78, 92, 104] L[1] Out[1]: 45 L[-4] Out[1]:45 |
Length of a List
len() function is used to find the length of a list.
L = [21, 45, 78, 92, 104] len(L) Out[1]: 5 L = [ ] len(L) Out[1]: 0 |
Concatenation of Lists
‘+’ operator is used to join two lists.
x=[10,20,30] y=[60,70,80] print(x+y) Out[1]: [10, 20, 30, 60, 70, 80] |
Replication of Lists
‘*’ operator can be used to repeat the elements of a list ‘n’ number of times. For a list l, for l*n, the list l will be repeated n times.
x=[10,20,30] x*2 Out[1]: [10, 20, 30, 10, 20, 30] x*3 Out[1]: [10, 20, 30, 10, 20, 30, 10, 20, 30] x*0 Out[1]: [ ] x*1 Out[1]: [10, 20, 30] x*1.5 TypeError: can't multiply sequence by non-int of type 'float' |
Slicing Lists
List slices are similar to string slices. They are a sub part of a list extracted from the main list.
L[start:stop:step]
Where all start, stop and step are optional.
L = [ 10, 12, 14, 20, 22, 24, 30, 32, 34 ]
Index: 0 1 2 3 4 5 6 7 8
L[30] -> Index Error : Index is out of bounds
List Slicing | Result |
L[3:9] | [20,22,24,30,32,34] |
L[3:-3] | [20,22,24] |
L[3:30] | [20,22,24,30,32,34] |
L[-15:7] | [10,12,14,20,22,24,30] |
L[-3:-2] | [30] |
L[4:-4] | [22] |
L = [ 2, 3, 4, 5, 6, 7, 8 ]
Index: 0 1 2 3 4 5 6
List Slicing | Result |
L[2:5] | [4,5,6] |
L[6:10] | [8] |
L[10:20] | [ ] |
L[-2:-4] | [ ] |
L[-2:-4:-1] | [7,6] |
L = [ 10, 12, 14, 20, 22, 24, 30, 32, 34 ]
Index: 0 1 2 3 4 5 6 7 8
List Slicing | Result |
L[0:10:2] | [10,14,22,30,34] |
L[2:10:3] | [14,24,34] |
L[::3] | [10,20,30] |
L[::-1] | [34,32,30,24,22,20,14,12,10] |
L[::2] | [10,14,22,30,34] |
L[5::2] | [24,32] |
Using List Slices for Modification
Slices can be used to overwrite one or more list elements.
L1=[10,12,14,20,22,24,30,32,34] L2 = L1[3:-3] print(L2) Out[1]:[ 20,22,24] L2[1]=28 print(L2) Out[2]:[20,28,24]
L1=[1,2,3] L1[2:]=”604” print(L1) Out[3]:[1,2,’6’,’0’,’4’] L1[2:]=345 TypeError: can only assign an iterable
L1=[1,2,3] L1[10:20]=”abcd” print(L1) Out[4]:[1,2,3,’a’,’b’,’c’,’d’] |
Comparing Lists
Two lists can be compared using relational operators like <, >, <=, >=, == etc.
Python internally compares individual elements of the list. Therefore, for two lists to be equal, both should have an equal number of elements of the same type and with the same value.
Comparing Lists | Result |
[1,2,8,9] < [9,1] | True |
[1,2,8,9] < [1,2,9,1] | True |
[1,2,8,9]<[1,2,9,10] | True |
[1,2,8,9]<[1,2,8,4] | False |
[1,2,8,9]<[1,2,8,9] | False |
[2,3]==[2,3] | True |
[2,3]==[‘2’,’3’] | False |
[2,3]>[2,3] | False |
[2.0,3.0]>[2,3] | False |
[2.0,3.0]==[2,3] | True |
[2,3]<[2,3,4] | True |
[1,2,3]==[1,2,3] | True |
[1,2,3]==[1,[2,3]] | False |