LISTS
LISTS
-------------
Advanced Datatypes:
Lists:
collection of datatypes (same
datatypes or other datatypes)
List can be created using [ ]
List index or position will starts from
zero
EX:
#LISTS
L=[]
type(L)
<class 'list'>
L=[10,20,30,40]
type(L)
<class 'list'>
M=[10,1.2,'hello',13,2+6j]
type(M)
<class 'list'>
operations on Lists:
1. append(): adding elements to a list (at the
end)
#append
A=[]
A.append(10)
A.append(20)
A.append(30)
A.append(40)
print(A)
[10, 20, 30, 40]
append() will add elements at the end only
so we can't add the elements in between or in
other places
4. update:
modifying list elements
syntax:
Listname[index]=new_value
ex:
#update
print(A)
[15, 20, 30, 40, 50]
A[0]=100
print(A)
[100, 20, 30, 40, 50]
A[1]=200
print(A)
[100, 200, 30, 40, 50]
A[2]=300
print(A)
[100, 200, 300, 40, 50]
5. Count:
It will give the number of elements in list
syntax:
len(Listname)
ex:
#count
len(A)
5
6. Repeat:
repeating elements in a list
syntax:
listname*n
ex:
#Repeat
print(A)
[100, 200, 300, 40, 50]
A*3
[100, 200, 300, 40, 50, 100, 200, 300, 40, 50, 100,
200, 300, 40, 50]
7. Accessing or printing:
By using index we can print the list elements
index will starts from 0 (Positive indexing)
index will starts from -1 (Negative indexing)
10. extend:
some what similar to merge
syntax:
List1.extend(List2)
ex:
C=[10,20,30]
D=[40,50,60]
C+D
[10, 20, 30, 40, 50, 60]
print(C)
[10, 20, 30]
C.extend(D)
C
[10, 20, 30, 40, 50, 60]
11. slicing:
accessing part of a list
syntax:
listname[leftindex:rightindex]
ex:
L[1:4]
L[1]
L[2]
L[3]
ex:
#slice
print(A)
[100, 200, 300, 40, 50, 10, 20, 30]
A[1:4]
[200, 300, 40]
A[2:4]
[300, 40]
A[:3]
[100, 200, 300]
A[1:]
[200, 300, 40, 50, 10, 20, 30]
print(A)
[100, 200, 300, 40, 50, 10, 20, 30]
12. sort:
arranging the elements in order
syntax:
List.sort()
ex:
#sort
print(A)
[100, 200, 300, 40, 50, 10, 20, 30]
A.sort()
print(A)
[10, 20, 30, 40, 50, 100, 200, 300]
#reverse
A.sort(reverse=True)
A
[300, 200, 100, 50, 40, 30, 20, 10]
13. copy
Syntax:
new_list=old_list