List
: list
is used to represent group of elements into a single entity or object.
Insertion order is preserved. Duplicate elements are allowed. Heterogeneous
elements are allowed. Every element in the list object is represented with
unique index. List supports both positive and negative indexes. We can perform
the operations on the elements of the list object by using ‘indexes’. We can create the list object by using ‘list()’ function and by using square
brackets ‘[ ]’. List objects are
mutable objects.
Example –
a=[]
print a
print type(a)
b=[10,20,30]
print b
print type(b)
x=list()
print x
print type(x)
y=list('rakesh')
print y
print type(y)
print a
print type(a)
b=[10,20,30]
print b
print type(b)
x=list()
print x
print type(x)
y=list('rakesh')
print y
print type(y)
Output –
[]
<type 'list'>
[10, 20, 30]
<type 'list'>
[]
<type 'list'>
['r', 'a', 'k', 'e', 's', 'h']
<type 'list'>
Example –
x=[10,20,'rakesh',True,123.123,10,'rakesh'] print x print id(x) y=[10,20,30,40,50] print y print id(y) print y[2] print y[2:4] print y[-2] print y[0:-3] y[2]=100 print y print id(y) del y[3] print y print id(y)
Output –
[10, 20, 'rakesh', True, 123.123, 10, 'rakesh']
43452136
[10, 20, 30, 40, 50]
43452456
30
[30, 40]
40
[10, 20]
[10, 20, 100, 40, 50]
43452456
[10, 20, 100, 50]
43452456
Example –
x=[100,123.123,'rakesh'] print x print len(x) a,b,c=x print a print type(a) print b print type(b) print c print type(c) y=[10,20,[100,200,300],'rakesh'] print y
Output –
[100, 123.123, 'rakesh']
3
100
<type 'int'>
123.123
<type 'float'>
rakesh
<type 'str'>
[10, 20, [100, 200, 300], 'rakesh']
Example –
x=['rakesh','guwahati','assam'] print x for p in x: print p,'---->',len(p) for q in p: print q
Output –
['rakesh', 'guwahati', 'assam']
rakesh ----> 6
r
a
k
e
s
h
guwahati ----> 8
g
u
w
a
h
a
t
i
assam ----> 5
a
s
s
a
m
Example –
x=[[10,20,30],[40,50,60],[70,80,90]] print x for p in x: for q in p: print q, print
Output –
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
10 20 30
40 50 60
70 80 90
Example –
x=[10,20,30] print x print id(x) y=[10,20,30] print y print id(y) print x==y print x is y z=y print z print id(z) print y==z print y is z
Output –
[10, 20, 30]
35718888
[10, 20, 30]
35719208
True
False
[10, 20, 30]
35719208
True
True
Example –
x=[10,20,30,40,50] print x print id(x) print len(x) x.append(60) print x print id(x) x.insert(2,70) print x y=['abc','def','xyz',30] print y x.extend(y) print x print x.index('abc') x.remove(30) print x x.sort() print x.pop() print x x.pop(3) print x print id(x)
Output –
[10, 20, 30, 40, 50]
38274792
5
[10, 20, 30, 40, 50, 60]
38274792
[10, 20, 70, 30, 40, 50, 60]
['abc', 'def', 'xyz', 30]
[10, 20, 70, 30, 40, 50, 60, 'abc', 'def', 'xyz', 30]
7
[10, 20, 70, 40, 50, 60, 'abc', 'def', 'xyz', 30]
xyz
[10, 20, 30, 40, 50, 60, 70, 'abc', 'def']
[10, 20, 30, 50, 60, 70, 'abc', 'def']
38274792
No comments:
Post a Comment