|
| 1 | +# Lists |
| 2 | + |
| 3 | +There is a data type very similar to tuples in Python. These are lists (`list`). Unlike tuples, which are constants, lists are structures that can change: you can add new elements to them, delete or change them. |
| 4 | + |
| 5 | +Lists with specific items are created similar to tuples, however, instead of parentheses, square brackets are used: |
| 6 | + |
| 7 | +```python |
| 8 | +list = ["first", 2, 2.5, 3-1j] |
| 9 | +``` |
| 10 | + |
| 11 | +As with tuples, the list items don't have to be of the same type. All the previous operations shown for tuples, such as iterating over them in a **for** loop, indexing elements, slices, and so on, work exactly the same for lists. |
| 12 | + |
| 13 | +However, the list items can be changed. Please enter the following commands in the interactive console |
| 14 | + |
| 15 | +```python |
| 16 | +list = [1, 2, 3] |
| 17 | + |
| 18 | +list[0] = 10 |
| 19 | + |
| 20 | +print(list) # [ 10 , 2, 3] |
| 21 | +``` |
| 22 | + |
| 23 | +If I did such an assignment for a tuple, it would cause a `TypeError`. |
| 24 | + |
| 25 | +List items can also be removed with a command **`del`**. E.g: |
| 26 | + |
| 27 | +```python |
| 28 | +list = ['A', 'B', 'C', 'D'] |
| 29 | + |
| 30 | +del list[1] # delete the second element |
| 31 | + |
| 32 | +print (list) # ['A', 'C', 'D'] |
| 33 | +``` |
| 34 | + |
| 35 | +It is also possible to insert and add items to the list. They are used to this method with names `insert` and `append`. These methods are specific operations related to a variable of a given type. They are similar to a function, but affect only one specific object. They are called as follows `object.method(arguments...)`, where object is usually a variable name, and the method name is separated from the object by a period. Adding an item to the list will look like this: |
| 36 | + |
| 37 | +```python |
| 38 | +list = ['A', 'B', 'C'] |
| 39 | + |
| 40 | +list.append('D') |
| 41 | +``` |
| 42 | + |
| 43 | +The method append puts the element given as its argument to the end of the list. So in the example above, the list would be `['A', 'B', 'C', 'D']`. In contrast, the method `insert` takes two arguments: the place where the element should be inserted (i.e. the index of the inserted element) and its value: |
| 44 | + |
| 45 | +```python |
| 46 | +list = ['A', 'B', 'C'] |
| 47 | + |
| 48 | +list.insert(1, 'X') |
| 49 | + |
| 50 | +print(list) # ['A', 'X', 'B', 'C'] |
| 51 | +``` |
| 52 | + |
| 53 | +Below is an example of creating a names list. Please run it and analyze it: |
| 54 | + |
| 55 | +``` |
| 56 | +names = [] # this creates an empty list |
| 57 | +
|
| 58 | +# The following loop will run infinitely |
| 59 | +# it can only be ended with break |
| 60 | +while True: |
| 61 | + name = input("Enter name or write a dot to end:") |
| 62 | + if name == '.': |
| 63 | + break |
| 64 | + names.append(name) |
| 65 | +
|
| 66 | +print(names) |
| 67 | +``` |
| 68 | + |
| 69 | +## Converting lists and other types |
| 70 | + |
| 71 | +You can convert lists to tuples and vice versa without any restrictions. This way, you can work around the restriction not allowing tuples to be modified: |
| 72 | + |
| 73 | +```python |
| 74 | +my_tuple = (1, 2, 3) |
| 75 | +my_list = list(my_tuple) |
| 76 | +list[0] = 10 |
| 77 | +my_tuple = tuple(my_list) |
| 78 | +print(my_tuple) |
| 79 | +``` |
| 80 | + |
| 81 | +However, keep in mind that tuples are more efficient and run faster, so avoid this conversion unless absolutely necessary. |
| 82 | + |
| 83 | +Similarly, you can convert strings into lists, but not the other way around: check what the following command will do `str(['a', 'b', 'c'])`. However, there are two very useful methods defined for strings: `split` and `join`. The method `split` is used to split a text string into words, and join to concatenate list items. Please try to split the text yourself in the interactive console: |
| 84 | + |
| 85 | +```python |
| 86 | +text = "one two three" |
| 87 | + |
| 88 | +list = text.split() |
| 89 | + |
| 90 | +print(list) # ['one', 'two', 'three'] |
| 91 | +``` |
| 92 | + |
| 93 | +There is also an alternate way of calling the method `split` that allows you to split text not into words (that is, at spaces and newlines), but selected strings. For example, let's see how to split a text containing words separated by a comma followed by a space: |
| 94 | + |
| 95 | +```python |
| 96 | +text = "one, two, three" |
| 97 | + |
| 98 | +list = text.split(', ') |
| 99 | + |
| 100 | +print(list) # ['one', 'two', 'three'] |
| 101 | +``` |
| 102 | + |
| 103 | +The method `join` (which works on text strings) is used to concatenate the elements of a list (or a tuple) given as its arguments. The hyphen is the text that this method works on. This is best illustrated by an example: |
| 104 | + |
| 105 | +```python |
| 106 | +list = ['Kacper', 'Melchior', 'Balthazar'] |
| 107 | + |
| 108 | +hyphen = "+" |
| 109 | + |
| 110 | +text = hyphen.join(list) |
| 111 | + |
| 112 | +print(text) # "Kacper+Melchior+Baltazar |
| 113 | +``` |
| 114 | + |
| 115 | +The methods also work directly for text values: |
| 116 | + |
| 117 | +```python |
| 118 | +list = ['Kacper', 'Melchior', 'Balthazar'] |
| 119 | + |
| 120 | +text = "+".join(list) |
| 121 | + |
| 122 | +print(text) # "Kacper+Melchior+Baltazar |
| 123 | +``` |
| 124 | + |
| 125 | +### Elegant list creation |
| 126 | + |
| 127 | +The method `append` is used to add items to the list. If it can be avoided, it is better not to use it to build entire lists, repeating it inside a for loop. Python offers an elegant method of creating lists called **list comprehension**. Above is an example of creating a list by listing its elements separated by a comma and placed in square brackets `[...]`. Instead of listing the items manually, you can use a for loop with the following syntax: |
| 128 | + |
| 129 | +```python |
| 130 | +list = [expression for counter in sequence] |
| 131 | +``` |
| 132 | + |
| 133 | +This expression comes before the **`for`** command and there is no colon anywhere. This expression can use a loop counter to compute successive values to insert into the list. It is best to illustrate this with an example. Suppose we want to create a list containing squares of numbers in the range 1-10: |
| 134 | + |
| 135 | +```python |
| 136 | +squares = [i**2 for i in range(1, 11)] |
| 137 | + |
| 138 | +print(squares) |
| 139 | +``` |
| 140 | + |
| 141 | +Please note that this is very similar to the natural language: "let the list of squares consist of the values i² for i in the range 1 to 10". |
| 142 | + |
| 143 | +In a more advanced version, we can add an additional condition that the loop counter must satisfy in order for the corresponding expression to be included in the list: |
| 144 | + |
| 145 | +```python |
| 146 | +list = [expression for counter in sequence if condition] |
| 147 | +``` |
| 148 | + |
| 149 | +For example, if we do not want to include the squares of 3 and 7 in our list of squares, we can write: |
| 150 | + |
| 151 | +```python |
| 152 | +squares = [i**2 for i in range(1, 11) if i not in (3, 7)] |
| 153 | +``` |
| 154 | + |
| 155 | +## Exercise |
| 156 | + |
| 157 | +Please write the shortest possible program, which will create a list containing the lengths of individual words in the sentence "To be or not to be" (for the sake of simplicity, punctuation marks have been omitted). |
| 158 | + |
| 159 | + |
| 160 | + |
| 161 | + |
| 162 | + |
| 163 | +<hr/> |
| 164 | + |
| 165 | +Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/) license. |
0 commit comments