Having learnt about tuples, you will now learn about lists, which are one of the widely used data structures; they offer flexibility in updating, deleting, adding operations and much more.
Most of the properties of lists are the same as those of tuples, except one major difference: Lists are mutable, which means the elements of a list can be changed. For more examples of indexing and slicing in lists, you can refer to the python documentation on lists.
Some of the important methods available with lists include:
extend(): Extend a list by adding elements at the end of the list
append(): Append an object to the end of a list
The major difference between the two methods is that the append() method takes an object passed as a single element and adds it to the end of the list, whereas extend() takes an object passed as an iterable and adds every element in the iterable at the end of the list.
# extend() L = ["Chemistry", "Biology", [1989, 2004] ,("Oreily" , "Pearson")] L.extend([5, 8]) L
# append() L = ["Chemistry", "Biology", [1989, 2004], ("Oreily" , "Pearson")] L.append([5, 8]) L
In the examples above, you can see that when a list is passed in the extend method, it takes each element from the list and appends it to the end of the list. However, when the same list is passed to an append method, it considers this list as a single element and appends it to the end of the list.
pop(index): Remove and return the item at index (default last)
remove(value): Remove the first occurrence of a value in the list
sort(): Stable sort *IN PLACE*
In the video above, you learnt about shallow copying, which is an important concept to understand while handling lists. As you saw, by assigning B = A, you refer to the same list object in the memory and the changes made to list A will be reflected in list B as well. With A[:], you are creating a new object and this new object is assigned to B; here, any changes in list A wouldn’t affect list B anymore.