Want to explore the data structures of Python in a real-world application? Try out the Build a Python Airline Reservation System project.
Key takeaways:
Lists are versatile and mutable, tuples are immutable for fixed data and sets efficiently handle unique, unordered data.
Lists, tuples, and sets can all store multiple data types, allowing dynamic data handling in Python programs.
The in
keyword works seamlessly across lists, tuples, and sets to quickly determine if an element exists.
Python is a high-level, object-oriented programming language widely used for building software, analyzing data, and automating tasks. As a general-purpose language, Python powers everything from websites to artificial intelligence and machine learning models. In this blog, we’ll introduce you to three of Python’s most common
For instance, a list in Python can mimic a bank queue, where people line up to be served by a bank representative on a FIFO (first in, first out) basis. This means the person at the front of the queue is served first, followed by each subsequent person in the exact order they joined the line. A list can also function as a stack, where the last item added is the first to be removed, following the LIFO (last in, first out) principle, similar to a stack of plates. These concepts are foundational in Python and can be applied to many real-life situations. If you’re new to Python, don’t worry—this Python tutorial is designed with beginners in mind.
A list in Python is a built-in data structure that allows us to store different data types sequentially. In Python, a list stores elements in a specific order, and each element can be accessed using its index. These indexes are zero-based, meaning the first element is at index 0. Lists shouldn’t be confused with linked lists, which organize data differently and are not specific to Python.
Lists also support negative indexing, allowing us to access elements from the end of the list, with -1
referring to the last element, -2
to the second last, and so on.
To help us understand better, let us use an example in which we want to create a list containing fruits sold in a grocery store. The fruit names must be comma-separated and enclosed in square brackets []
. The code below shows our fruit list:
fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']print(fruits_list)
The example above shows that our fruit list starts with Apple
and ends with Guava
.
If we want to include repeated elements in a list, we can do so because lists in Python allow duplicate elements. Three key distinguishing attributes of lists are that they are mutable, ordered, and allow duplicates.
By mutable, we mean that elements in a list can be inserted, removed, or modified, allowing the list to change. When we say lists are ordered in Python, their elements appear in a fixed sequence when accessed.
Lists allow us to do more exciting things, such as iterating, accessing, adding, and removing elements from them. When working with this data structure, we should all be familiar with these basic list manipulation techniques.
Let’s use our example above to perform these operations!
We can use a for
loop to iterate over a list. For example, we can print each element of the given list:
fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']for fruit in fruits_list:print(fruit)
Here, each element is printed separately. Iterating over lists allows us to perform additional operations, such as converting fruit names to uppercase or extracting specific names into a separate list.
List elements are accessed using an index, a number representing their position. Let us look at an example:
fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']print(fruits_list[2])
Here, we passed the index 2
to access the element at that position. Remember, indexes in lists start at 0
, not 1
.
As lists are mutable, you can update them. Therefore, we can add, remove, and change elements within a list.
We can add a new element at the end of the list using the append()
function, for instance, as shown below:
fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']fruits_list.append('Pear')print(fruits_list)
We can also remove elements by their value in the list via the remove()
function:
fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']fruits_list.remove('Banana')print(fruits_list)
We can also change elements in a list directly:
fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']fruits_list[3] = 'Grapes'print(fruits_list)
Other methods used while working with lists are as follows:
len()
returns the length of the list passed to the function.
count()
returns how many times a value passed as an argument appears in the list.
sort()
converts an unsorted list to a sorted list.
Dynamic data: Use lists when the data is expected to change, such as when you need to add, remove, or modify elements.
Ordered collection: Ideal for maintaining the sequence of elements like task lists, timelines, or steps in a process.
Versatile operations: Choose lists for operations requiring slicing, indexing, or iteration in a predictable order.
Lists are highly flexible and adaptable, making them a go-to choice for working with ordered, mutable data in Python.
Note: To further enhance your understanding of lists, dive deeply into Python’s data structures.
In Python, tuples are also built-in data structures that hold a collection of elements. We also enclose a tuple in parentheses ()
and separate the elements with a comma. While similar to lists, tuples have some distinct characteristics:
Ordered: The order of elements in a tuple is fixed.
Immutable: Once created, tuples cannot be modified. Immutability is one of a tuple’s key traits, disallowing removal, addition, or change of elements.
Duplicates: Tuples can contain duplicates.
Tuples in Python are defined using parentheses ()
, and their elements are separated with commas. Here is an example:
fruits_tuple = ('Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava')print(fruits_tuple)
Like lists, we can perform basic operations on tuples like iteration, indexing, and accessing.
Like their list counterparts, tuples have zero-based indexing. Therefore, index 0 is used to access the first element of a non-empty tuple. A negative index like -1 accesses elements starting from the end.
Consider the example below:
fruits_tuple = ('Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava')print(fruits_tuple[2])print(fruits_tuple[-1])
Similarly, we can iterate over each tuple element using a for
loop.
fruits_tuple = ('Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava')for i in fruits_tuple:print(i)
Iterating tuples in Python can be useful for many reasons, such as checking tuple length or accessing a specific data type.
Other common methods used in tuples include the following:
len()
measures the length of a tuple.
count()
returns how many times an element occurs in a tuple.
index()
finds the position of the first occurrence of an element.
These methods are simple yet effective for analyzing and interacting with tuple data in Python.
Fixed data: Use tuples for unchangeable data like coordinates, configuration settings, or constant values.
Performance: Opt for tuples over lists when memory efficiency or immutability is required.
Tuples are simple yet powerful data structures that provide security and efficiency for fixed data collection.
A set in Python is a built-in data structure that can hold multiple elements at once. Regarding its features, the sets are:
Enclosed in curly braces {}
.
Unordered, meaning their elements have no specific sequence.
Duplicate-free, ensuring each element is unique.
Here’s an example of a Python set:
employee_set = {'Charlie Brown', 'Kaylee Rust', 'Holy Ronald', 'Kris Troy', 'Georgina Depp'}print(employee_set)
You cannot use {}
to create an empty set, as it creates an empty dictionary instead. Instead, you must use the set()
function:
empty_set = set()print(empty_set) # Output: set()
Operations performed on sets range from iterating to modifying elements present in the set. We will examine a few examples below.
Although sets are unordered, you can still iterate through them using a for
loop:
employee_set = {'Charlie Brown', 'Kaylee Rust', 'Holy Ronald', 'Kris Troy', 'Georgina Depp'}for employee in employee_set:print(employee)
As we know, sets are mutable, so that we can modify them. However, you cannot use indexing to access or change items because they are unordered.
We can use the add()
method to add an element to the set and remove()
to eliminate an element from a set. For instance:
employee_set = {'Charlie Brown', 'Kaylee Rust', 'Holy Ronald', 'Kris Troy', 'Georgina Depp'}employee_set.add('Kamala Haris')print(employee_set)
To use the remove()
method on our set, we can do the following:
employee_set = {'Charlie Brown', 'Kaylee Rust', 'Holy Ronald', 'Kris Troy', 'Georgina Depp'}employee_set.remove('Kaylee Rust')print(employee_set)
Because sets in Python are, by default, unordered, indexing cannot be used to access or change an item in a set.
Other common methods used in sets include:
len()
measures the length of a set.
clear()
empties the content of a set.
update()
adds multiple items to a set.
Unique data: Use sets, such as user IDs or tags, to store unique items and automatically remove duplicates.
Unordered collections: Sets are best for situations where order is irrelevant but quick membership testing or set operations like union, intersection, and difference are needed.
Efficient comparisons: Sets are excellent for comparing collections or identifying relationships between data, like shared or distinct elements.
Sets efficiently manage unique and unordered data, offering speed and simplicity for tasks involving membership and comparison.
Learn Python Data Structures
Data structures and algorithms are among the most fundamental concepts of Computer Science. Whether it’s real-world problems you’re trying to solve or the typical coding question asked in an interview, almost every problem requires you to demonstrate a deep understanding of data structures and algorithms. This course is a detailed review of some of the most common data structures and algorithms that you’ll see in interviews and your everyday work. With implementation details, thorough explanations, and hands-on coding exercises, you’ll quickly gain the confidence you need to solve any problem, no matter the situation.
Did you have fun learning about Python lists, tuples, and sets? Let’s summarize our findings of all three data structures:
Lists | Tuples | Sets |
Uses square brackets [] | Uses parentheses () | Uses curly braces {} |
Duplicates are allowed | Duplicates are allowed | Duplicates are not allowed |
Mutable | Immutable | Mutable |
Ordered | Ordered | Unordered |
Congratulations on diving headfirst into Python’s built-in data structures! However, we only touched on the basic features of lists, tuples, and sets. Several more data structures and methods come in handy for different applications you may want to explore, such as dictionaries- which operate on key-value pairs, hash maps, hash tables, graphs- which work with vertices, and more.
Now that you have a good understanding of Python lists, tuples, and sets, you may want to enhance your knowledge further and explore data structures in more depth. The good news is that whether you’re a beginner in Python or want to build up your developer portfolio, Educative has a range of fully interactive, hands-on Python courses that will surely hone your Python skills and make you a solid developer.
Happy learning!
Can tuples have duplicates?
What are the differences between lists, tuples, and sets in Python?
How do I choose between a list, set, or tuple for a specific task?
Free Resources