Get up to 80 % extra points for free! More info:

Lesson 1 - Python Collections - Tuples and Lists

Welcome to the first part of course about collections in Python. In this part, we'll deepen our knowledge of lists and learn to use tuples.

Tuples

Creating Tuples

A tuple is a data type that stores its elements in a certain order. It's created as follows:

empty = ()
empty_2 = tuple()
other = (1, 2, 3)
other_2 = tuple(range(3))

We can create a tuple by placing its elements in parentheses and separating the individual elements with a comma. The expression tuple() can also convert other data types to tuples (if possible), such as the result of the range() function.

The range() and zip() functions

Tuples can also be created using range() and zip(). For example, let's create a tuple with odd numbers:

odd = tuple(range(1, 10, 2))
even = tuple(range(0, 10, 2))

When we print the tuples, we'll see this:

Console application
>>> odd = tuple(range(1, 10, 2))
>>> even = tuple(range(0, 10, 2))
>>> odd
(1, 3, 5, 7, 9)
>>> even
(0, 2, 4, 6, 8)
>>>

We can use the zip() function to create tuples that contain other tuples from multiple iterators of the range() function. It sounds complicated, so let's take a look at an example:

Console application
>>> my_tuple = tuple(zip(range(1, 5, 1), range(2, 8, 3), range(1, 7, 2)))
>>> my_tuple
((1, 2, 1), (2, 5, 3))
>>>

A tuple containing only two tuples was created here. The number of nested tuples is given by the smallest number of elements returned by one of the range() functions - in this case the second one, because:

the first one returns - 1, 2, 3, 4

the second one returns - 2, 5

the third one returns - 1, 3, 5

The smallest one is the second tuple - so the first two elements are taken from each tuple so tuples (1, 2, 1) and (2, 5, 3) are formed.

And that's all about the zip() and range() functions.

Operators

We'll show first that tuples can be joined (+), replicated (*) and tested to see if there is (are) an element in them. In the following example, we create two tuples, one with odd and the other with even digits. We'll then connect the two.

Console application
>>> odd = tuple(range(1, 10, 2))
>>> odd
(1, 3, 5, 7, 9)
>>> even = tuple(range(0, 10, 2))
>>> even
(0, 2, 4, 6, 8)
>>> numbers = odd + even
>>> numbers
(1, 3, 5, 7, 9, 0, 2, 4, 6, 8)
>>>

We can also replicate sets, which means that we "multiply" them:

>>> numbers = tuple(1, 2, 3)
>>> numbers * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Additionally, we can find out whether a given element is (is not) in the tuple:

>>> numbers = tuple(1, 2, 3)
>>> 1 in numbers
True
>>> 4 in numbers
False
>>> 2 not in numbers
False
>>> 5 not in numbers
True

Trimming a Tuple and the len() Function

Only a certain part of the tuple can be extracted from one. E.g. we only need the first two elements. How to do it?

Each element in the tuple has its own serial number (the place where it's stored - an index). The first element has the number 0, the next 1, etc. We find the element in the tuple as follows - the name of the tuple[element number] - e.g. my_tuple[1] - the element in the second place.

Example:

Console application
>>> my_tuple = ("a", 2, 3.0, "d", 5.0)
>>> my_tuple[0]
'a'
>>> my_tuple[1]
2
>>> my_tuple[2]
3.0
>>> my_tuple[3]
"d"
>>> my_tuple[4]
5.0
>>>

The number of elements in the tuple is determined by the len() function. Since the indexing is zero-based, the last element has the number len(*the name of the tuple*) - 1. The len() function returns an integer indicating the number of elements.

And another example:

Console application
>>> my_tuple_1 = (1, 2, 3)
>>> len(my_tuple_1)
3
>>> my_tuple_2 = (1, "a", 1.0, "A")
>>> len(my_tuple_2)
4
>>> my_tuple_3 = ()
>>> len(my_tuple_3)
0
>>>

Elements from the tuple can also be obtained by negative indices. With negative indices, numbering "goes" from the end to the beginning. Therefore, the last element has the index -1, the second to last has -2 and so on, and the first element has the index -len(*the name of the tuple*).

Example:

Console application
>>> my_tuple = tuple(range(10))
>>> my_tuple
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> my_tuple[0]
0
>>> my_tuple[9]
9
>>> my_tuple[-1]
9
>>> my_tuple[-10]
0
>>> my_tuple[-len(my_tuple)]
0
>>> my_tuple[-2]
8
>>> my_tuple[-3]
7
>>> my_tuple[-4]
6
>>>

In the example, we created tuples using the range() function :) We can use trimming ([]) a little better. Imagine that you need to get all the elements in the tuple from the first to the third one (from index 0 to index 2). The syntax of trimming is similar to the syntax of the range() function:

  • my_tuple[m] - returns the element with index m from the tuple
  • my_tuple[m:n] - returns the elements with indices from m to n-1 from the tuple
  • my_tuple[m:n:i] - returns the elements with indices from m and every other i-th element up to n from the tuple

m, n and i can also be omitted. In this case, for example, [:] can return all elements.

Now a few examples to make it clear:

Console application
>>> my_tuple = tuple(range(10))
>>> my_tuple
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> my_tuple[0]
0
>>> my_tuple[1]
1
>>> my_tuple[:]
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> my_tuple[1:5]
(1, 2, 3, 4)
>>> my_tuple[1:7:2]
(1, 3, 5)
>>> my_tuple[::-1]
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
>>>

Tuples can also be compared using comparison operators (see Lesson 3), but the data types in the tuple must be comparable. The comparison takes place between individual elements until one of the elements at the same index position is greater (or lesser). This tuple is then greater (or lesser).

Methods

The methods are used by writing: my_tuple.method(*parameter*) :) Tuples have two methods: count() and index(). The count(*element*) method returns the number of occurrences of the specified element in the tuple, and the index(*element*) method returns the lowest non-negative index that contains the specified element.

Example:

Console application
>>> my_tuple = (1, 2, "a", 4, 1, "a", 1)
>>> my tuple.count(1)
3
>>> my_tuple.count("a")
2
>>> my_tuple.count(2)
1
>>> my_tuple.count(3)
0
>>> my_tuple.index(1)
0
>>> my_tuple.index("a")
2
>>> my_tuple.index(4)
3
>>>

That's all for tuples :) Now onto the lists.

Lists

We can use everything mentioned above for the lists, as well as other functions and methods. This is because lists differ from tuples in the way that elements can be added to the end of a list, because lists, unlike tuples, don't have a fixed size. You can add, delete and overwrite elements in the list. In Python, a list is created using brackets. You can also convert another data type (if possible) to a list of list() functions.

Now let's look at a few examples:

empty = []
empty_2 = list()
other = [1, 2, 3]
other_2 = list(range(3))

List elements are overwritten by the following syntax - list_name[element] = another_element.

Example:

Console application
>>> my_list = [1, 2, "a", 4.0]
>>> my_list[0]
1
>>> my_list[0] = 3
>>> my_list
[3, 2, 'a', 4.0]
>>> my_list[0:2] = [4, "b"]
>>> my_list
[4, 'b', 'a', 4.0]
>>> my_list[3] = list(range(3))
>>> my_list
[4, 'b', 'a', [0, 1, 2]]
>>> my_list[3][1]
1
>>> my_list[3][1] = 2
>>> my_list
[4, 'b', 'a', [0, 2, 2]]
>>>

At the end, we added another list to the list :) We can also work with list elements using loops. For example, to print individual list elements:

for element in my_list:
    print(element)

But if we want to go through the list gradually and do something with the elements, the following syntax is better:

for index in range(len(my_list)):
    my_list[index] = #here we can do whatever we need with the individual elements

Example - we have an array with different values and we want to increase the values e.g. by 1:

my_list = [1, 5, 2, 4, 6, 3]
for index in range(len(my_list)):
    my_list[index] = my_list[index] + 1

And the result is [2, 6, 3, 5, 7, 4] :)

Methods

We can use the count(element) and index(element) methods for a list, and many others, which we'll show:

append(element)

Appends an element to the end of the list.

clear()

Deletes all elements in the list.

copy()

Creates a deep copy of a list. For example, if you create a new list by referring to it with the = (shallow copy) operator, only the reference to the object is copied. In practice, this means that if you change the original list, the newly created list will also change. The variables - although they have a different name, actually point to the same thing :) This method creates a deep copy, so if you change the original list, the copied one will not change at all.

extend()

Appends all elements from the iterable object (list, tuple, etc.) to the end of a list.

insert(position, element)

Inserts an element at the given position.

pop(position)

Returns the value of the element at a given position and at the same time removes the element from the list. If no position is specified, it returns the value of the last element and deletes it.

remove(element)

Removes the first occurrence of an element from the list.

reverse()

Reverses the order of the elements in a list. The first element will be the last one, the second one the second to last... and the last one will be the first.

sort()

Without arguments, it sorts comparable elements in ascending order. This method takes two arguments: key (a function through which the elements are "passed" and then compared) and reversed (if set to True, the list is sorted in descending order). The sorted() function has the same key arguments.

List Comprehensions

They are used to create collections faster. They have the following syntax:

[expression for element in iterable_object]

Creates a new list of expressions.

[expression for element in iterable_object if condition]

Creates a new list of expressions. If the condition is met for the given expression, then the expression will be in the list.

Examples:

Console application
>>> my_list_1 = [number for number in range(10)]
>>> my_list_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> my_list_2 = [number * 2 + 1 for number in range(10)]
>>> my_list_2
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> my_list_3 = [number * 2 + 1 for number in range(10) if number % 3 == 0]
>>> my_list_3
[1, 7, 13, 19]
>>> my_list_4 = [number * 3 for number in range(50) if number % 2 == 0]
>>> my_list_4
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120, 126, 132, 138, 144]
>>>

In the next lesson, Iterators, Generators and Some Functions in Python, we'll show lambda functions, iterators and generators, and a few built-in functions.


 

All articles in this section
Collections in Python
Skip article
(not recommended)
Iterators, Generators and Some Functions in Python
Article has been written for you by Shift
Avatar
User rating:
No one has rated this quite yet, be the first one!
As an author I'm interested mainly in industry automation. I'm also writing music and literature. In my spare time I'm working on a few games in Game Maker Studio.
Activities