Python lists, tuples, and sets are common data structures that hold other objects. Let’s see how these structures are similar and how they are different by going through some code examples.
In Python, we have four built-in data structures that can store a collection of different elements. These are lists, dictionaries, tuples, and sets. If you already know the theory behind these data structures, you can go to our Python Data Structures in Practice course and get hands-on experience with the most frequent ways they’re used. In this article, we’ll focus on Python lists, tuples, and sets and explore their similarities and differences.
Python Lists
A Python list is a built-in data structure that holds a collection of items. To understand how lists work, let’s go straight to the example.
We want to create a list that includes names of the US presidents elected in the last six presidential elections. List elements should be enclosed in square brackets [] and separated by a comma. To create a list, we can simply write elements in square brackets:
us_presidents_list = ['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George W. Bush', 'George W. Bush']
The elements of this list appear in a specific order and start from the current president. If a president was elected twice (served for two terms), we include him twice. Here, we leverage two important characteristics of lists: lists are ordered and can contain duplicates.
When working with a list, you can iterate over it, access its elements, and also add, change, and remove list elements. These are the basic techniques that you can learn in our Python Data Structures in Practice course. Now, let’s go through a couple of examples:
Iterating over the list. By iterating over the list, we can perform a particular operation (e.g.
print
) with each element of the list:for president in us_presidents_list: print(president)Output:Joe BidenDonald TrumpBarack ObamaBarack ObamaGeorge W. BushGeorge W. Bush
Accessing list elements. We can access a list element through its index position:
print(us_presidents_list[1])Output:Donald Trump
In Python, indexing starts with 0. Thus, we accessed the second element of the list using index 1.
Modifying lists. Lists are mutable, implying that we can add, remove, and change their elements. For example, we can use
append()
to add a new element at the end of the list:us_presidents_list.append('Bill Clinton')print(us_presidents_list)Output:['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George W. Bush', 'George W. Bush', 'Bill Clinton']
We can remove any element of the list with the
remove()
method:us_presidents_list.remove('Bill Clinton')print(us_presidents_list)Output:['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George W. Bush', 'George W. Bush']
We can also change the individual list elements by accessing them with indices:
us_presidents_list[4] = 'George Bush'print(us_presidents_list)Output:['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George Bush', 'George W. Bush']
Here, we have printed out each element separately. By iterating over the list, we could also change all names to uppercase or extract last names into a separate list.
If you work a lot with numerical data, you may want to use arrays rather than lists. Learn how Python lists are different from arrays in this article.
Python Tuples
A Python tuple is another built-in data structure that can hold a collection of elements. Tuples are technically very similar to lists. However, they usually have different applications; while lists mainly contain a collection of different items, tuple elements often correspond to one record.
For example, it would be more common to store basic information about one US president (rather than a list of US presidents) in one tuple. So, let’s create a us_president_tuple
. A tuple can be created by placing all the elements inside parentheses (), separated by commas:
us_president_tuple = ('Joe', 'Biden', '2021-01-20', 'Democratic')
Here, we have included the president’s first name, last name, date of inauguration, and political party. These elements appear in a specific order – tuples are ordered. We don’t have duplicate elements in our tuple, but you can store duplicates in Python tuples.
Now, let’s perform some basic operations with our tuple. We can iterate over it and access its elements with indexing:
Iterating over the tuple. Like with lists, we can print out each element of our tuple separately by iterating over it:
for i in us_president_tuple: print(i)Output:JoeBiden2021-01-20Democratic
We can do many other things when iterating over tuple elements, e.g. checking that the length of each element doesn’t exceed a particular value, accessing the data type of each tuple item, etc.
Accessing tuple elements. We can access tuple elements using indexing. For example, let’s get the inauguration date:
print(us_president_tuple[2])Output:2021-01-20
Using index 2, we’ve printed out the third element of the tuple, which is the inauguration date.
By accessing tuple elements, we can also get the full name of the current US president:
print(us_president_tuple[0], ‘ ‘, us_president_tuple[1])Output:Joe Biden
Unlike lists, tuples are immutable. This data structure doesn’t allow changing, adding, or removing individual elements.
Python Sets
A Python set is a built-in data structure in Python that, like lists and tuples, holds multiple elements. To understand how it’s different from lists and tuples, let’s go through another example.
We’ll create a set called us_presidents_set
with the names of US presidents. One of the ways to create a Python set is to define it with curly braces {}:
us_presidents_set = {'Bill Clinton', 'Joe Biden', 'Donald Trump', 'Barack Obama', 'George W. Bush'}
The names of five US presidents are included in random order because sets are unordered. Also, sets cannot contain duplicates; thus, all the names are included only once, no matter how many terms that person served as president.
Let’s have a couple of code examples to see how sets work in practice.
Iterating over the set. We can iterate over a set to print its elements using the exact same code snippet we used with lists:
for president in us_presidents_set: print(president)Output:George W. BushJoe BidenBill ClintonDonald TrumpBarack Obama
Note that the order of the elements printed in the output is different from the order we specified when creating this set. That’s because, as we mentioned, sets are an unordered collection of items.
We may also iterate over this set to check whether we have ‘Ronald Reagan’ in the set.
reagan = Falsefor president in us_presidents: if president == 'Ronald Reagan': reagan = Trueprint(reagan)Output:False
Here, we start by creating a dummy variable,
reagan
, that’s equal toFalse
. (This is assuming that we don’t have Ronald Reagan in the set.) Then, we check every set element to see if any is equal to ‘Ronald Reagan
’. If there is a set element equal to ‘Ronald Reagan
’, thereagan
variable will change toTrue
. As you see from the output, thereagan
variable is still equal toFalse
, showing that this president is not included in the set.Modifying sets. Sets are mutable, allowing us to add and remove their elements. To add a single element to the set, simply use the
add()
method:us_presidents_set.add('George H. W. Bush')print(us_presidents_set)Output:{'George W. Bush', 'Joe Biden', 'Bill Clinton', 'Donald Trump', 'George H. W. Bush', 'Barack Obama'}
To remove any element of the set, use the remove() method:
us_presidents_set.remove('Bill Clinton')print(us_presidents_set)Output:{'George W. Bush', 'Joe Biden', 'Donald Trump', 'George H. W. Bush', 'Barack Obama'}
Considering that Python sets are unordered, we cannot access or change an individual element of a set using indexing.
Learn more about Python set operations in this comprehensive guide.
Wrap-Up: The Difference Between Lists, Tuples, and Sets in Python
Now, let’s summarize what we’ve learned so far about Python lists, tuples, and sets:
Python lists | Python tuples | Python sets |
---|---|---|
list = [item1, item2, item3] | tuple = (item1, item2, item3) | set = {item1, item2, item3} |
ordered | ordered | unordered |
allow duplicates | allow duplicates | no duplicates |
mutable | immutable | mutable |
These are the basic characteristics of Python lists, tuples, and sets. There are more features that can influence which data structure is preferable for a particular application. Also, do not forget about Python dictionaries, yet another built-in data structure that can hold a collection of items.
To learn more about lists, tuples, sets, and dictionaries, check out our interactive Python Data Structures in Practice course. It contains 118 exercises that cover typical use cases for each of the data structures discussed in this article. You’ll also learn about nested lists, which can be used to represent 2D images, tabular data, or virtual game boards. At the end of the course, you’ll write an actual PC game!
For those willing to take a comprehensive approach to learning Python, we recommend the track Learn Programming with Python. It includes five fully interactive courses that cover Python basics and some more advanced topics.
Still not sure if you need to learn Python? Read this article to see why Python is your must-learn in 2021.
Thanks for reading and happy learning!