Lists
- The list is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets, e.g.:)
myList = [1, None, True, "I am a string", 256, 0]
- Lists can be indexed and updated, e.g.:
myList = [1, None, True, 'I am a string', 256, 0] print(myList[3]) # outputs: I am a string print(myList[-1]) # outputs: 0 myList[1] = '?' print(myList) # outputs: [1, '?', True, 'I am a string', 256, 0] myList.insert(0, "first") myList.append("last") print(myList) # outputs: ['first', 1, '?', True, 'I am a string', 256, 0, 'last']
- Lists can be nested, e.g.:
myList = [1, 'a', ["list", 64, [0, 1], False]]
- List elements and lists can be deleted, e.g.:
myList = [1, 2, 3, 4] del myList[2] print(myList) # outputs: [1, 2, 4] del myList # deletes the whole list
- Lists can be iterated through using the for loop, e.g.:
myList = ["white", "purple", "blue", "yellow", "green"] for color in myList: print(color)
- The len() function may be used to check the list’s length, e.g.:
myList = ["white", "purple", "blue", "yellow", "green"] print(len(myList)) # outputs 5 del myList[2] print(len(myList)) # outputs 4
-
A typical function invocation looks as follows:
result = function(arg)
, while a typical method invocation looks like this:result = data.method(arg)
. - A new element may be glued to the end of the existing list:
list.append(value)
Such an operation is performed by a method named append(). It takes its argument’s value and puts it at the end of the list which owns the method.
The list’s length then increases by one.
- The insert() method is a bit smarter - it can add a new element at any place in the list, not only at the end.
list.insert(location, value)
It takes two arguments:
- the first shows the required location of the element to be inserted; note: all the existing elements that occupy locations to the right of the new element (including the one at the indicated position) are shifted to the right, in order to make space for the new element;
- the second is the element to be inserted.