pyt3
pyt3
Now that we've covered the basic data types in Python, let's start covering the built-in data
structures. First, we have lists.
To define a list, we use square brackets [] with the elements separated by a comma.
💡 Tip: It's recommended to add a space after each comma to make the code more readable.
[1, 2, 3, 4, 5]
["a", "b", "c", "d"]
[3.4, 2.4, 2.6, 3.5]
Lists can contain values of different data types, so this would be a valid list in Python:
my_list = [1, 2, 3, 4, 5]
letters = ["a", "b", "c", "d"]
Nested Lists
Lists can contain values of any data type, even other lists. These inner lists are called nested
lists.
>>> my_list[0]
[1, 2, 3]
>>> my_list[1]
[4, 5, 6]
Nested lists could be used to represent, for example, the structure of a simple 2D game board
where each number could represent a different element or tile:
List Length
We can use the len() function to get the length of a list (the number of elements it contains).
For example:
>>> len(my_list)
4
<list_variable>[<index>] = <value>
For example:
>>> letters
['z', 'b', 'c', 'd']
We can add a new value to the end of a list with the .append() method.
For example:
>>> my_list.append(5)
>>> my_list
[1, 2, 3, 4, 5]
For example:
>>> my_list.remove(3)
>>> my_list
[1, 2, 4]
💡 Tip: This will only remove the first occurrence of the element. For example, if we try to
remove the number 3 from a list that has two number 3s, the second number will not be
removed:
>>> my_list.remove(3)
>>> my_list
[1, 2, 3, 4]
List Indexing
We can index a list just like we index strings, with indices that start from 0:
>>> letters[0]
'a'
>>> letters[1]
'b'
>>> letters[2]
'c'
>>> letters[3]
'd'
List Slicing
We can also get a slice of a list using the same syntax that we used with strings and we can
omit the parameters to use their default values. Now, instead of adding characters to the slice,
we will be adding the elements of the list.
<list_variable>[start:stop:step]
For example:
>>> my_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> my_list[2:6:2]
['c', 'e']
>>> my_list[2:8]
['c', 'd', 'e', 'f', 'g', 'h']
>>> my_list[1:10]
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> my_list[4:8:2]
['e', 'g']
>>> my_list[::-1]
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> my_list[::-2]
['i', 'g', 'e', 'c', 'a']
>>> my_list[8:1:-1]
['i', 'h', 'g', 'f', 'e', 'd', 'c']