Lists
List definition
Lists are objects that represent a collection of objects, which can be of any data type (including data structures). Lists are mutable objects, which means we can add new elements into the list, delete existing elements from the list, or change each element’s value.
A list can be created with assignment using [ ], inside of which we define the contained elements (separated with , ). Elements of the list can be of any data type, including another list or some other complex data type.
List can be created using command list, whose arguments are iterable objects, such as strings, lists, tuples and dictionaries.
An empty list is created with [] (without any elements).
>>> list1 = [1, 2, 3, 4]
>>> print(list1)
[1, 2, 3, 4]
>>> list2 = ['Gengar', 6.54, True, [3, 5, 7]]
>>> print(list2)
['Gengar', 6.54, True, [3, 5, 7]]
>>> list3 = list("abcd12345")
>>> print(list3)
['a', 'b', 'c', 'd', '1', '2', '3', '4', '5']
Accessing list elements
Elements of a list can be accessed individually by their index, which represents their position in the list and goes from 0 to n-1, where n is the list’s length (command len returns length of our list). Attribute command index returns the index of the supplied element: list.index(element_value).
Accessing an element is done by stating list_name[index]. Index -i represents i-th element going from the opposite end of the list (for example, the last element in the list matches index -1). Index which is out of range will signal an error.
>>> bulls = ['Jordan', 'Pippen', 'Rodman', 'Kukoc']
>>> print(bulls.index('Rodman'))
2
>>> print(bulls[1], bulls[2], bulls[-1], bulls[-4])
Pippen Rodman Kukoc Jordan
>>> print(bulls[4]) #index 4 is out of range
IndexError: list index out of range
Accessing multiple elements of the list at the same time is called slicing. Slicing can be done with start-index, end-index and step by stating list[start_index:end_index:step].
Start-index refers to element we’re starting from, including that element. End-index refers to the last element and we’re not including it in the process. Step refers to the indexes we will keep in the slicing. If the value of step is 1, we will keep every element from start_index till end_index – 1. If the value of step was 2, we will keep every second element and so on. By default the value of step is 1, which is done just by stating the start and end index (without the second “:”).
We don’t need to state all three values if we’re accessing successive elements. We can put : followed by some index i, which means we’re accessing the first i elements, and that can be written as list[:i]. If we instead put : after the the index i, which means we’re accessing elements starting from the element with index i, and that can be written as list[i:]. If we state list[:], we will access all the elements (easier than writing [0:n]). These values can also be negative, but only in the range of the list length.
If the step value is negative, that means our slicing direction is from right-to-left, opposite of the usual. If we try slicing from lower index to higher with negative step, result will be empty list [].
>>> prehistoric = ['Smilodon', 'Megatherium', 'Andrewsarchus', 'Indricotherium', 'Hyaenodon', 'Mammoth']
>>> print('Carnivores:', prehistoric[0:5:2]) """print every second element starting from index 0
to 5 not including index 5"""
Carnivores: ['Smilodon', 'Andrewsarchus', 'Hyaenodon']
>>> print('Herbivores:', prehistoric[5:0:-2]) """print every second element starting from index 5
to 0 not including index 5"""
Herbivores: ['Mammoth', 'Indricotherium', 'Megatherium']
>>> print('First three:', prehistoric[:3]) #print first three elements
['Smilodon', 'Megatherium', 'Andrewsarchus']
>>> print('Last four:', prehistoric[-4:]) #print last 4 using negative index
['Andrewsarchus', 'Indricotherium', 'Hyaenodon', 'Mammoth']
>>> print('Herbivores, but reversed:', prehistoric[-1:-6:-2]) """we used negative index to print
herbivores in reverse order"""
Herbivores, but reversed: ['Mammoth', 'Indricotherium', 'Megatherium']
>>> print('Reversed order:', prehistoric[::-1]) """excluding start and end will print all the
elements; using a negative step value will put the in reverse order"""
Reversed order: ['Mammoth', 'Hyaenodon', 'Indricotherium', 'Andrewsarchus', 'Megatherium', 'Smilodon']
Iteration and membership
Iteration through list is done using for loop. Membership to list can be tested with membership operators in or not in, which return True if an element belongs to our list, otherwise they return False.
>>> cnt = 0
>>> xfactor = 'Leonard'
>>> clippers2021 = ["George", "Jackson", "Morris", "Zubac", "Batum"]
>>> for i in clippers2021:
if i == xfactor:
cnt += 1
break
>>> if cnt == 0:
print('Clippers lose to Suns by 4-2.')
Clippers lose to Suns by 4-2.
>>> if xfactor not in clippers2021:
print('No championship again.')
No championship again.
Adding new elements
Adding new element(s) to list can be done in multiple ways:
–command list – argument must be an iterable object (list or string)
–concatenation – can be used to create a new list from two or more existing lists (addition) or to add new elements to the existing list (add-and-assign)
–attribute command list.append(new) – we can add single element new to the end of the list; new can be a single value or a list
–attribute command list.extend(new_el1, new_el2, …) – we can add multiple new elements new_el1, new_el2, etc. to the end of the list (same as concatenation)
–attribute command list.insert(index, new_element) – we can add a single element new_element to the stated position index in the list
–replication – we can multiply a list with an integer value, multiplying the number of the elements by that value
>>> numbers = list([1, 2, 3, 4])
>>> print(numbers)
[1, 2, 3, 4]
>>> numbers += [5, 6]
>>> print(numbers)
[1, 2, 3, 4, 5, 6]
>>> numbers.append(7)
>>> print(numbers)
[1, 2, 3, 4, 5, 6, 7]
>>> numbers.insert(0, 0)
>>> print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> numbers.append(8, 9)
TypeError: append() takes exactly one argument (2 given)
>>> numbers.extend(8,9)
>>> print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers.append([10, 11, 12])
>>> print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 12]]
>>> arr = [2, 4, 6] * 2
>>> print(arr)
[2, 4, 6, 2, 4, 6]
Deleting elements
Deleting elements from a list can also be done in multiple ways:
–command del – we can delete a single element or more elements (only by slicing)
–attribute command list.pop(i) – we can remove a single element with index i from the list and assign its value elsewhere (optional)
–attribute command list.remove(val) – we can remove a single element with value val from the list
>>> del(numbers[6:])
>>> print(numbers)
[0, 1, 2, 3, 4, 5]
>>> a = numbers.pop(3)
>>> print(a, numbers)
3 [0, 1, 2, 4, 5]
>>> numbers.remove(4)
>>> print(numbers)
[0, 1, 2, 5]
Changing element values
Elements of the list can be given new values individually or with slicing.
>>> grades = [6, 6, 7, 7, 7, 8]
>>> grades[1:4] = [8, 9, 10]
>>> print(grades)
[6, 8, 9, 10, 7, 8]
>>> grades[4] = 10
>>> print(grades)
[6, 8, 9, 10, 10, 8]
Commands for workings with lists
These are some useful commands that can make some jobs easier to do. Among them, there are standard commands that we used in the previous lesson, but also attribute commands, which are specific to certain data types and they are stated after the variable identifier: var.attribute(arg1, arg2).
List of some useful commands:
–command len – returns the length of the list
–command sum – sums the values of all elements in the list; if even one value is not numeric, the program signals an error
–command min – compares the values of all elements and returns the lowest value; if even one value is not numeric, the program signals an error
–command max – compares the values of all elements and returns the greatest value; if even one value is not numeric, the program signals an error
–attribute command list.reverse() – returns the list with reverse order of the elements
–attribute command list.sort() – sorts the list elements in ascending order; if even one value is not numeric, the program signals an error
–command sorted – returns a new list with sorted elements; elements can be sorted in ascending or descending order; if even one value is not numeric, the program signals an error
–attribute command list.count(val) – counts the number of elements with the value val stated as an argument
–attribute command list.copy() – creates a shallow copy of the list
>>> list = [15, 4, 9, 7, 15, 23, 5]
>>> print(len(list))
7
>>> print(min(list), max(list))
4 23
>>> print(sum(list))
78
>>> print(list.reverse())
[5, 23, 15, 7, 9, 4, 15]
>>> print(list.sort())
[4, 5, 7, 9, 15, 15, 23]
>>> print(list.count(15))
2
>>> new_list = list.copy()
>>> print(new_list)
[4, 5, 7, 9, 15, 15, 23]
Table of contents
- Functions
- Collections
- Exceptions
- Input & Output
- RegEx & PRNG
- Classes And Objects
- Popular Libraries
- Additional Problems