Tuesday, December 23, 2014

Modifying list

Here we will now see how to modify a list:

>>>list=[2,3,4,5,"Hello",97,32,"Hey","World",12]
>>>list
[2,3,4,5,'Hello',97,32,'Hey','World',12]

#here the list is not sorted
>>>print sorted(list)
[2,3,4,5,12,32,97,'Hello','Hey','World']

'''
Here you can observe that the number is first sorted then the strings are sorted
'''
>>>print list
[2,3,4,5,'Hello',97,32,'Hey','World',12]

'''
Now you observe that after printing sorted(list) again printing list is not printing the sorted one because we have not modified the list. We have just printed the list.
To modify list look next step
'''
>>>list=sorted(list)
>>>print list
[2,3,4,5,12,32,97,'Hello','Hey','World']

'''
Suppose we want to modify the list on some particular index
actually its a very easy task'''
>>>list[3]=17
>>>print list
[2,3,4,17,12,32,97,'Hello','Hey','World']
>>>list[-1]=14
>>>print list
[2,3,4,5,12,32,97,'Hello','Hey',14]
''' Now we want to add some elements in the list'''
>>>list.append(37)
>>>print list
[2,3,4,5,12,32,97,'Hello','Hey',14,37]
NOTE: The new element is added at the -1 location.

#list.append(37) is equivalent to list[len(list):]=[37]
#len(list) returns the list size.

>>>list.insert(3,94)
'''it inserts an item in the given location. The first argument decides the location. Second argument is the data item which is to be inserted.'''
>>>list
[2,3,4,94,5,12,32,97,'Hello','Hey',14,37]
>>>del list[2]
#it deletes the item at the give index location
>>>list
[2,3,94,5,12,32,97,'Hello','Hey',14,37]


No comments:

Post a Comment