Lists and Tuples in Python for Beginners
Imagine you’re making a guest list for a wedding. This list is constantly changing: family friends Dima and Sveta have been added, but cousins on the wife’s side, Lida and Natasha, cannot attend.
Lists are perfect for representing such real-world data in Python. Lists are another built-in data type in Python.
You can create, or declare, a list in Python in two ways:
my_list = list()
or:
my_list = []
Let’s return to the wedding guests. To create a guest list, you can immediately place strings with names inside the brackets, separated by commas.
guests = ['Parents', 'Classmates', 'Lida and Natasha']
print(guests)
List Element Operations
Our list contains three elements: “Parents”, “Classmates”, “Lida and Natasha”, stored in this specific order. Unless you change the order of the list, “Parents” will always be the first element, “Classmates” the second, and “Lida and Natasha” the third. “Parents” represents the start of the list, and “Lida and Natasha” the end. We remember that Lida and Natasha cannot come, and they need to be removed from the list.
You can remove the last element in the list using the remove method.
guests = ['Parents', 'Classmates', 'Lida and Natasha']
print(guests) # ['Parents', 'Classmates', 'Lida and Natasha']
guests.remove("Lida and Natasha")
print(guests) # ['Parents', 'Classmates']
But don’t forget, we also need to add two guests to the list. Adding new elements to the end of the list is done using the append method.
guests = ['Parents', 'Classmates', 'Lida and Natasha']
print(guests) # ['Parents', 'Classmates', 'Lida and Natasha']
guests.remove("Lida and Natasha")
print(guests) # ['Parents', 'Classmates']
guests.append('Dima')
guests.append('Sveta')
print(guests) # ['Parents', 'Classmates', 'Dima', 'Sveta']
You can not only add an element to a list but also change one of its values according to the element’s index.
guests = ['Parents', 'Classmates', 'Dima', 'Sveta']
print(guests) # ['Parents', 'Classmates', 'Dima', 'Sveta']
guests[2] = 'Colleagues'
print(guests) # ['Parents', 'Classmates', 'Colleagues', 'Sveta']
So, a list is a container that holds objects in a specific order. Note that unlike strings, list methods modify the original list. However, lists have something in common with strings: access by index and slicing. All of this works in lists just like it does in strings.
guests = ['Parents', 'Classmates', 'Dima', 'Sveta']
print(guests[0]) # Parents
print(guests[-1]) # Sveta
print(guests[:2]) # ['Parents', 'Classmates']
Tuples
Tuples are containers that hold objects in a specific order. Unlike lists, tuples are immutable.
Once you create a tuple, you cannot change the value of any of its elements, nor can you add or remove elements. Tuples are declared using parentheses. Elements in a tuple should be separated by commas.
Tuples can also be created using one of two syntax options. The first:
my_tuple = tuple()
And the second:
my_tuple = ()
To add new objects to a tuple, create it using the second method, specifying each desired element separated by a comma.
data = ('I. Ivanov', 1958, True)
print(data) # ('I. Ivanov', 1958, True)
Even if a tuple contains only one element, you still need to put a comma after this element. This way, Python distinguishes a tuple from a number in parentheses, which define the order of operations.
You can access tuple elements just like you do with list elements, by specifying the element’s index.
books = ("1984", "Brave New World", "Fahrenheit 451")
print(books[2]) # Fahrenheit 451
The in / not in Keyword
You can check if an element is contained in a tuple using the in keyword.
books = ("1984", "Brave New World", "Fahrenheit 451")
print("1984" in books) # True
print("Dunno on the Moon" in books) # False
Place the not keyword before in to check for the absence of an element in a tuple.
books = ("1984", "Brave New World", "Fahrenheit 451")
print("Dunno on the Moon" not in books) # True
The same operations with the in and not in keywords will work with lists as well.
Concatenating Tuples and Lists
You can concatenate two identical data structures using the addition operator. The example below with lists will also work with tuples:
colors1 = ["blue", "green", "yellow"]
colors2 = ["orange", "pink", "black"]
print(colors1 + colors2) # ['blue', 'green', 'yellow', 'orange', 'pink', 'black']
At this point, you might wonder why use data structures that seem less flexible than lists? In fact, tuples are convenient when dealing with values that will never change. An example of such data for a tuple could be geographic coordinates. The longitude and latitude of a city should be stored in a tuple because these values will never change, and storing them in a tuple ensures that other parts of the program do not accidentally modify them.
Iterating
Strings, lists, and tuples support iteration (the program can go through them value by value), meaning each of their elements can be accessed through a loop—such objects are called iterable. Each element in an iterable object, as we already know, has its own ordinal index.
In the following example, the element Moscow is listed with index 0, Helsinki with index 1, and 'Ankara' with index 2.
cities = ['Moscow', 'Helsinki', 'Ankara']
for city in cities:
print(city)
# Moscow
# Helsinki
# Ankara
Here we are introduced to the for operator—a loop that iterates over an iterable object. The for loop can be used to define instructions that will be executed once for each element in the iterable object, and with such instructions, you can access all these elements and perform operations with them.
For example, using a for loop that iterates over a list of strings and the upper method, you can make the characters of each string uppercase:
cities = ['Moscow', 'Helsinki', 'Ankara']
for city in cities:
print(city.upper())
# MOSCOW
# HELSINKI
# ANKARA
As shown in the examples above, the for loop is defined with the syntax: for variable_name in iterable_object_name:, where variable_name is the name you choose for the variable that will hold each value from the iterable object during each iteration of the loop.