Mutable and Immutable objects
Chapter 7
Data structure
Group of data elements define under an identifier
●
Way of organizing and storing data in computer
●
Compound data structure
●
Integer, number etc.. are simple data
●
String is a sequence type and made of characters, is
●
ordered set. Elements are indexed
– Immutable data object
Others are list, set, tuples, dictionary
●
LIST
● An ordered sequence of elements seperated by comma.
● Non-scalar data type
● Syntax : list1=[val1,val2,..valn]
● Example: subject=['maths','hindi','physics','english']
● typing subject gives
●>>>subject
['maths', 'hindi', 'physics', 'english']
Elements of list may not be same, hence is called
●
Heterogeneous list
● list1=[1,2,’abc’,’xyz’]
subject=['maths','hindi','physics','english']
Each list variable has an id and is retrieved using id(list1)
●
Accessing element of a list and slicing
●
seq=list1[start:end:increment]
●
e.g.
subject[3] -> 'english'
●
subject[2::2] -> ['physics']
●
subject[1::] -> ['hindi', 'physics', 'english']
●
● subject[::2] -> ['maths', 'physics']
●Aliasing object i.e. temp=subject : both refers to same
location and hence same values
Aliasing object
● Different variable refering to same object
● id(subject) -> 140334996962312
● id(list1) -> 10731488
● list1=subject
● id(list)1 -> 140334996962312
● subject[2]; list1[2] -> 'physics'
'physics'
Input list from the keyboard using
string
names=eval(input('enter details:'))
enter details:'megha',90,'34b/ua' #string is entered
names -> ('megha', 90, '34b/ua')
names=eval(input('enter details:'))
enter details:['megha',90,'34b/ua'] #list is entered
names -> ['megha', 90, '34b/ua']
names[2] -> '34b/ua'
Operations on list
Find the output?
list1=[4,5,1]; list1
list1.insert(1,3)
list1[2:2]=[6,8]
List1 #slicing at index 2 and insering in case first ● Click to add Text
element in range is >= 2nd element [4, 5, 1]
List1[2:4]=[15,17]; list1 #just replacing [4, 3, 5, 1]
[4, 3, 6, 8, 5, 1]
cubes=[]
[4, 3, 15, 17, 5, 1]
for i in range(1,5):
cubes.append(i**3) [1, 8, 27, 64]
print(cubes) [1, 4, 9, 16]
cubes=[i**2 for i in range(1,5)] [12, 8, 10]
print(cubes) [9]
list1=[12,8,9,10]
list2=[i for i in list1 if i%2==0]
print(list2)
list3=[i for i in list1 if i%2!=0]
print(list3)
List Comprehensions
● Shorthand notation to create list
● Eaxmple on nested list:
– list1=[[1,’ab’],[2,’bb’],[4,’cd’]]
– l1=[x for x in list1 if x[0]%2 ==0]