Learn Python: Lists, sets, and tuples

Jul 15, 2022 - 7 min read
Sadia Suhail
editor-page-cover

Python is a high-level object-oriented programming language used to build software, analyze data, and automate tasks. Python is a general-purpose language, so it can be used to create virtually any software, website, artificial intelligence platform, machine learning model, and so on. Python is also widely used in data science and data analysis and is only growing in popularity with programmers, surpassing other languages like Java. There is no greater time than now to learn Python. In this section, we will introduce you to the three most common types of data structures in this programming language. A data structure organizes data within a computer program so that it can be used efficiently.

A real-world example of a Python data structure in action is a bank queue where everyone lines up to be served by a bank representative based on a FIFO (First In, First Out) basis. This means that the person in the front of the queue will be served first, and the last person in the queue will be served last. Conversely, a stack of plates where the last plate added is the first one to be removed based on the LIFO (last-in/first-out) principle, which ensures that the last element is popped out first and vice versa. You can apply these algorithms to more of your real-life situations as you become proficient with them. This article is for beginners, so don’t worry if you’re new to Python.

We’ll cover the following:


What are lists in Python?

A list in Python is a built-in data structure that allows us to store different data types sequentially. In Python programming, a list contains addresses assigned to every element in the list. These addresses are known as indexes. By default, an index value of a non-empty list begins at 0. Also, lists shouldn’t be confused with linked lists because the latter are not stored sequentially in memory but rather use pointers and nodes to reference data.

Lists also support negative indexing, which allows us to access elements from last to first and is denoted by -1.

To help us understand better, let us use an example in which we want to create a list containing fruits. These elements will be enclosed in square brackets [] and separated with a comma. The code below shows our fruit list:

fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava'] 
print(fruits_list)

From the example above, we can see that our fruit list starts with Apple and ends with Guava. If we want to repeat an element, we can because lists are mutable and allow duplicates. The two key distinguishing attributes of lists are that they are ordered and allow duplicate elements.

We say lists are ordered in Python because although the objects they contain are mutable, the order of these objects is fixed, meaning that you will only be able to add new things at the end of the list.

We can also do more exciting things with lists, such as iterating, accessing, adding, and removing elements from the list. These are basic list manipulation techniques we should all be familiar with when working with this data structure.

Let’s use our example above to perform these operations!

Iteration

We can use certain operations such as print() to iterate over our list. Based on our example, we can iterate over each element in the list using a for loop here:

fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']
for fruit in fruits_list: 
 print(fruit)

Here each element has been printed separately. With list iteration, we can perform more operations such as changing fruit names to uppercase or extracting names to another list altogether.

Accessing elements

List elements are accessed via the index position. Let us look at another example:

fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']
print(fruits_list[2]) 

Here, we passed the index value 2 to access the element at that position. Remember, indexes in lists start at 0, not 1.

Modifying elements

We earlier learned that a main characteristic of lists is being mutable. 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 via their index position:

fruits_list = [ 'Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava']
fruits_list[3] = 'Grapes' 
print(fruits_list) 

More functions

More methods used while working with lists are:

  • len() returns the length of the list
  • count() displays the count of the list value passed
  • sort () converts an unsorted list to a sorted list

You can further enhance your understanding of lists from this article on Educative.

What are tuples?

In Python, tuples are also built-in data structures that hold a collection of elements. They are similar to lists but have a few key differences. The main difference between a tuple and a list is that tuples are ordered and immutable while lists are mutable. Immutability is one of a tuple’s key traits, disallowing any removal, addition, and changing elements. They can also contain duplicates.

We also enclose a tuple in parentheses () and not square brackets [] and separate them with a comma.

Lets dive into an example:

fruits_tuple = ('Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava') 
print(fruits_tuple)

Like lists, we can also perform basic operations like iteration, indexing, and accessing on tuple elements.

Accessing tuple elements

Like their list counterparts, tuples too have zero-based indexing. Therefore, the first element of a positive non-empty tuple will be [0] by default. And a negative [-1] index count will begin from the end of the tuple.

Consider the example below:

fruits_tuple = ('Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava') 
print(fruits_tuple[2]) 
print(fruits_tuple[-1])

Iterating tuple elements

Similarly, we can iterate over each tuple element. We have used a for loop in the example below to iterate over our tuple:

fruits_tuple = ('Apple', 'Banana', 'Pineapple', 'Orange', 'Strawberry', 'Kiwi', 'Guava')
for i in fruits_tuple: 
 print(i) 

Iterating tuples in Python can be done for many reasons, such as checking tuple length, accessing a specific data type, and so on.

What are sets?

A set in Python is another built-in data structure that can hold several elements at once. Sets are similar to lists and tuples but have a distinct syntax. For example, sets are enclosed in curly braces {}, cannot have duplicate elements, and contain an unordered collection of items.

Let’s look at a Python set below:

employee_set = {'Charlie Brown', 'Kaylee Rust', 'Holy Ronald', 'Kris Troy', 'Georgina Depp'} 
print(employee_set) 

Operations performed on sets range from iterating and modifying elements present in the set. We will take a look at a few examples below.

Modifying set elements

Since we know that sets are mutable, we can modify them as per our choice. We can use add() 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.

More 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

Lists vs sets vs tuples: differences and similarities

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

Congrats on diving headfirst into Python’s built-in data structures! However, we only touched on the basic features of lists, tuples, and sets. There are several more data structures and methods which 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.

Where to go from here

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 Educative has a fully interactive hands-on Data Structures and Algorithms in Python course, which will surely hone your Python skills and make you a solid developer.

Additionally, you may want to look at more courses on the Educative platform that introduce you to the fundamentals of Data Structures for Coding Interviews in Python. If you are still rusty, don’t forget to check out Educative’s hands-on Python Fundamentals course.

Happy learning!

Continue learning about Python


WRITTEN BYSadia Suhail

Join a community of more than 1 million readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.