Last active
April 27, 2020 08:06
-
-
Save adityadev11/a12007fe986838f28f024a8617ab9eee to your computer and use it in GitHub Desktop.
Blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Lists in python | |
#Lists are created using [] | |
List1=[1,2,3,"Hello",5.5,1+2j] #List1 having 6 elements | |
List2=[3,4,"World",1.0] #List2 having 4 elements | |
print("List1=",List1,'\n',"List2=",List2) | |
#To find lenght of list, we use len() | |
print("The length of List1-",len(List1)) | |
#To add any element at end of the list, we use append() | |
List1.append("new_element") | |
print("List1 after adding new element",List1) | |
#To insert an element anywhere in list,we use insert() with index where it is to be inserted. All other elements shift accorindly | |
List2.insert(3,"inserted_element") #inserting new element in index 3 | |
print("List2 after inserting-",List2) | |
#To access any element, we use <listname>[i] where i is the element index. | |
print("4th element of List1 is given by",List1[3]) | |
#To access a group of elements(list slicing),we use <list name>[i:j] where i is starting index | |
# and j is ending index which is not included | |
print("2nd,3rd and 4th element of List2 is given by",List2[2:5]) | |
#To change any element , simply assing a new value to any index (because Lists are Mutable) | |
List1[3]="Hey" | |
print("List1 after changing its 4th element-",List1) | |
#To delete an element by index, we use pop() or del[], and by value ,we use remove | |
# (pop returns valuee of element being deleted whereas del does not) | |
List1.pop(5) #deleting last element of List1 | |
del List1[0] #deleting first element of List1 | |
List2.remove("World") #deleting by value | |
print("List1 after deletions-",List1,'\n',"List2 after deletion-",List2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment