|
| 1 | +#This program gives examples about various list operations |
| 2 | + |
| 3 | +#Syntax: list[start: end: step] |
| 4 | + |
| 5 | +myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 6 | +#index 0 1 2 3 4 5 6 7 8 |
| 7 | +# -9 -8 -7 -6 -5 -4 -3 -2 -1 |
| 8 | + |
| 9 | +#List Slicing |
| 10 | +print('Original List:',myList) |
| 11 | +print('First Element:',myList[0]) #Prints the first element of the list or 0th element of the list |
| 12 | +print('Element at 2nd Index position:',myList[2]) #Prints the 2nd element of the list |
| 13 | +print('Elements from 0th Index to 4th Index:',myList[0: 5]) #Prints elements of the list from 0th index to 4th index. IT DOESN'T INCLUDE THE LAST INDEX |
| 14 | +print('Element at -7th Index:',myList[-7]) #Prints the -7th or 3rd element of the list |
| 15 | + |
| 16 | +#To append an element to a list |
| 17 | +myList.append(10) |
| 18 | +print('Append:',myList) |
| 19 | + |
| 20 | +#To find the index of a particular element |
| 21 | +print('Index of element \'6\':',myList.index(6)) #returns index of element '6' |
| 22 | + |
| 23 | +#To sort the list |
| 24 | +myList.sort() |
| 25 | + |
| 26 | +#To pop last element |
| 27 | +print('Poped Element:',myList.pop()) |
| 28 | + |
| 29 | +#To remove a particular element from the lsit BY NAME |
| 30 | +myList.remove(6) |
| 31 | +print('After removing \'6\':',myList) |
| 32 | + |
| 33 | +#To insert an element at a specified Index |
| 34 | +myList.insert(5, 6) |
| 35 | +print('Inserting \'6\' at 5th index:',myList) |
| 36 | + |
| 37 | +#To count number of occurences of a element in the list |
| 38 | +print('No of Occurences of \'1\':',myList.count(1)) |
| 39 | + |
| 40 | +#To extend a list that is insert multiple elemets at once at the end of the list |
| 41 | +myList.extend([11,0]) |
| 42 | +print('Extending list:',myList) |
| 43 | + |
| 44 | +#To reverse a list |
| 45 | +myList.reverse() |
| 46 | +print('Reversed list:',myList) |
0 commit comments