View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Types of Data Structures in Python: List, Tuple, Sets & Dictionary

By Rohit Sharma

Updated on Feb 04, 2025 | 14 min read | 11.8k views

Share:

Python provides four key data structures: Lists, Tuples, Sets, and Dictionaries, each optimized for specific use cases. Lists store ordered, mutable collections, while Tuples offer immutable sequences for fixed data. Sets handle unique, unordered elements, useful for removing duplicates, and Dictionaries store key-value pairs for fast lookups. 

This guide covers their properties with data structure in Python example. Let’s get started!

What is a List in Python?

A list in Python is a collection of ordered, mutable elements that can store items of any data type, making it a versatile data structure for various applications. It allows for easy manipulation of data, from adding or removing items to sorting or slicing.

Let's take a closer look at the key features that make lists unique and useful in Python:

  • Mutable: Lists can be changed after creation, allowing you to add, remove, or modify elements.
  • Ordered: The order of elements in a list is preserved, meaning you can access them by their index.
  • Can store duplicate values: Unlike sets, lists allow repeated elements, which can be useful in some situations.
  • Can store elements of different data types: Lists offer the flexibility to hold integers, strings, booleans, and more, all in one collection.

The syntax for creating a list is simple: 

list_name = [element1, element2, element3, ...]

List Operations in Python

With the basic syntax in mind, let's see how you can manipulate lists in Python.

  • Adding elements: Use .append() to add an item at the end of the list or .insert() to place it at a specific index.
  • Removing elements: Use .remove() to delete an item by its value or .pop() to remove an item by index.
  • Indexing and slicing: Access individual elements by their index or extract a portion of the list using slicing.
  • Sorting and reversing: Use .sort() to arrange the list in ascending order and .reverse() to reverse the order.

Let’s put everything into practice with an example: 

# Creating a list with integers and floats
my_list = [10, 3.14, 2, 7, 5]

# Adding elements
my_list.append(8)  # Adding 8 to the end
my_list.insert(2, 6)  # Inserting 6 at index 2

# Removing elements
my_list.remove(3.14)  # Removing 3.14 from the list
popped_item = my_list.pop(1)  # Popping the item at index 1 (6)

# Indexing and Slicing
first_item = my_list[0]  # Accessing the first item
slice_example = my_list[1:3]  # Slicing the list from index 1 to 2

# Sorting and Reversing
my_list.sort()  # Sorting the list
my_list.reverse()  # Reversing the list

# Output
print(my_list)
print(f"Popped item: {popped_item}")
print(f"First item: {first_item}")
print(f"Sliced example: {slice_example}")

Output: 

my_list = [8, 7, 6, 5, 2, 10]
popped_item = 6
first_item = 8
slice_example = [7, 6]

Explanation:

  • Adding elements:
    • append(8) adds 8 to the end of the list.
    • insert(2, 6) inserts 6 at index 2, shifting other elements.
  • Removing elements:
    • remove(3.14) removes 3.14 from the list.
    • pop(1) removes and returns the item at index 1, which is 6.
  • Indexing and Slicing:
    • my_list[0] retrieves the first item in the list (8).
    • my_list[1:3] returns a new list containing items from index 1 to 2 ([7, 6]).
  • Sorting and Reversing:
    • sort() arranges the list in ascending order ([2, 5, 6, 7, 8, 10]).
    • reverse() reverses the list, producing [10, 8, 7, 6, 5, 2].

Edge Cases to Consider

While lists are quite flexible, there are a few edge cases that might catch you off guard:

  • Sorting with Mixed Data Types: Attempting to sort a list with both numbers and strings will result in a TypeError because Python can't compare these two types.

Example: 

mixed_list = [3, 'apple', 5]
mixed_list.sort()  # This will raise a TypeError
  • Removing Non-Existent Elements: Trying to remove an element that doesn't exist in the list will raise a ValueError.

Example: 

my_list = [1, 2, 3]
my_list.remove(4)  # This will raise a ValueError

If you're looking to refine your skills and enhance your software engineering expertise, upGrad's Software Engineering course can help you master advanced techniques like Binary Search and more. 

Also Read: Python Program to Convert List to String

Now that you've mastered lists, let’s dive into tuples, which provide an immutable alternative for handling data in Python.

What is a Tuple in Python?

tuple in Python is an ordered, immutable collection of elements, which makes it useful when you need to ensure the integrity of your data. Unlike lists, once a tuple is created, it cannot be modified, which is ideal for storing constant data.

Let’s dive into the key features that make tuples distinct and beneficial in Python:

  • Immutable: Once created, tuples cannot be altered (no adding, removing, or modifying elements).
  • Ordered: Tuples maintain the order of elements, so you can access them by their index.
  • Can store duplicate values: Like lists, tuples can have repeated elements.
  • Can store elements of different data types: Tuples can hold integers, strings, booleans, and more in one collection.

The syntax for creating a tuple is: 

tuple_name = (element1, element2, element3, ...) 

Tuple Operations in Python

Let’s explore some common operations and manipulations you can perform on tuples.

  • Accessing elements: Use indexing to access individual elements by their position.
  • Slicing: You can slice a tuple to get a portion of the elements.
  • Concatenation: Combine multiple tuples into one. These are useful when you need to create a new tuple without modifying the original.
  • Repetition: Repeat a tuple using the multiplication operator *.

Let’s apply these operations in an example: 

# Creating a tuple with mixed data types
my_tuple = (10, 'apple', 3.14, True, 'banana')

# Accessing elements
first_item = my_tuple[0]  # Accessing the first item

# Slicing
slice_example = my_tuple[1:3]  # Slicing the tuple from index 1 to 2

# Concatenation
new_tuple = my_tuple + ('cherry', 'grape')  # Concatenating another tuple

# Repetition
repeated_tuple = my_tuple * 2  # Repeating the tuple

Output: 

first_item = 10
slice_example = ['apple', 3.14]
new_tuple = (10, 'apple', 3.14, True, 'banana', 'cherry', 'grape')
repeated_tuple = (10, 'apple', 3.14, True, 'banana', 10, 'apple', 3.14, True, 'banana')

Explanation:

  • Accessing elements:
    • my_tuple[0] retrieves the first item in the tuple (10).
  • Slicing:
    • my_tuple[1:3] returns a new tuple containing items from index 1 to 2 (['apple', 3.14]).
  • Concatenation:
    • my_tuple + ('cherry', 'grape') combines the original tuple with a new one containing "cherry" and "grape".
  • Repetition:
    • my_tuple * 2 creates a new tuple that repeats the original tuple twice.

Edge Cases to Consider

While tuples are very efficient, there are a few edge cases to keep in mind:

  • Attempting to Modify a Tuple: Trying to modify an element of a tuple will raise a TypeError since tuples are immutable.

Example: 

my_tuple = (1, 2, 3)
my_tuple[0] = 10  # This will raise a TypeError
  • Index Out of Range: Accessing an index that doesn’t exist in the tuple will raise an IndexError.

Example: 

my_tuple = (1, 2, 3)
my_tuple[5]  # This will raise an IndexError

Also Read: List vs Tuple: Understanding the Differences in Python

Now that you understand the immutability and benefits of tuples, let’s move on to explore sets, another versatile data structure in Python.

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree18 Months

Placement Assistance

Certification8-8.5 Months

What is a Set in Python?

set in Python is an unordered collection of unique elements, making it ideal for operations where the uniqueness of items is essential. Sets are mutable, meaning you can add and remove elements, but unlike lists, they don’t store duplicates. Sets use hash tables to store unique values. If you add a duplicate, it is automatically discarded. 

Let’s explore the key features that define sets in Python:

  • Unordered: Sets do not maintain the order of elements, meaning you cannot access elements by their index.
  • Unique elements: Sets automatically remove duplicate values, ensuring that each element appears only once.
  • Mutable: You can add or remove elements after the set is created.
  • Can store elements of different data types: While sets can store elements of various types, all elements must be immutable (e.g., numbers, strings, and tuples).

The syntax for creating a set is simple: 

set_name = {element1, element2, element3, ...} 

Set Operations in Python

Now that you know the basic syntax of sets, let’s take a closer look at common operations you can perform on sets.

  • Adding elements: Use .add() to add a single element to a set.
  • Removing elements: Use .remove() to delete an element by value, or .discard() to remove an element without raising an error if the element doesn’t exist.
  • Set union, intersection, and difference: Use .union(), .intersection(), and .difference() to perform mathematical set operations.
  • Set membership: Use the in keyword to check if an element exists in the set.

Let’s dive into an example to see these operations in action: 

# Creating a set with mixed data types
my_set = {10, 'apple', 3.14, True, 'banana'}

# Adding elements
my_set.add('cherry')  # Adding 'cherry' to the set

# Removing elements
my_set.remove('apple')  # Removing 'apple' from the set
my_set.discard('grape')  # Discarding 'grape' (no error even though 'grape' is not in the set)

# Set operations
set2 = {20, 'orange', 'banana', 3.14}
union_set = my_set.union(set2)  # Union of my_set and set2
intersection_set = my_set.intersection(set2)  # Intersection of my_set and set2
difference_set = my_set.difference(set2)  # Difference between my_set and set2

# Set membership
is_banana_in_set = 'banana' in my_set  # Checking if 'banana' is in the set

Output: 

my_set = {True, 10, 3.14, 'banana', 'cherry'}
union_set = {True, 10, 3.14, 'apple', 'banana', 'cherry', 20, 'orange'}
intersection_set = {3.14, 'banana'}
difference_set = {True, 10, 'cherry'}
is_banana_in_set = True

Explanation:

  • Adding elements:
    • add('cherry') adds "cherry" to the set. Sets only store unique elements, so if you try to add "cherry" again, it won't be added.
  • Removing elements:
    • remove('apple') removes "apple" from the set.
    • discard('grape') does not raise an error even though "grape" is not in the set.
  • Set operations:
    • union() combines all elements from both sets and removes duplicates.
    • intersection() returns elements that are present in both sets.
    • difference() returns elements that are in the first set but not in the second.
  • Set membership:
    • 'banana' in my_set returns True because "banana" is indeed in the set.

Edge Cases to Consider

While sets are a powerful tool in Python, there are some important edge cases to keep in mind:

  • Unordered nature: Since sets do not maintain order, you cannot access elements using indices or guarantee the order in which they are stored.

Example: 

my_set = {1, 2, 3}
print(my_set[0])  # This will raise a TypeError
  • Mutability of sets: While sets are mutable, the elements inside a set must be immutable. You cannot store lists or dictionaries inside a set.

Example: 

my_set = {[1, 2], 'apple'}  # This will raise a TypeError
  • Attempting to add duplicates: Sets automatically discard duplicates, so adding a duplicate element will have no effect.

Example: 

my_set = {1, 2, 3}
my_set.add(2)  # The set remains {1, 2, 3}

Also Read: What is Mutable and Immutable in Python? Definitions, Data Types, Examples, and Key Differences

Now that you understand how sets work, let’s explore dictionaries, another powerful data structure in Python.

upGrad’s Exclusive Data Science Webinar for you –

Transformation & Opportunities in Analytics & Insights

 

What is a Dictionary in Python?

A dictionary in Python is an unordered collection of key-value pairs, each key unique. It is a highly efficient data structure that allows for fast lookups, inserts, and updates. The keys in a dictionary act like indexes, while the values hold the corresponding data.

Let’s break down the key features of dictionaries:

  • Unordered: Dictionaries do not maintain the order of elements. However, starting from Python 3.7, dictionaries are insertion-ordered, meaning they preserve the order in which items are added (though this is not the primary purpose).
  • Key-Value Pairs: Each item in the dictionary is a pair consisting of a unique key and its associated value.
  • Mutable: You can change the contents of a dictionary by adding, removing, or updating key-value pairs.
  • Keys are immutable: Dictionary keys must be of an immutable data type, such as strings, numbers, or tuples.

The syntax for creating a dictionary is simple: 

dict_name = {key1: value1, key2: value2, ...}

Dictionary Operations in Python

Now that you know the basic structure of a dictionary, let's explore some of the common operations you can perform on dictionaries.

  • Adding or Updating elements: Use the assignment operator to add new key-value pairs or update existing ones.
  • Removing elements: Use .pop() to remove an element by key or .popitem() to remove and return a random key-value pair.
  • Accessing values: You can access values by referring to their keys.
  • Keys, values, and items: Use .keys(), .values(), and .items() to get the keys, values, or both as pairs from the dictionary.

Dictionaries use hash tables to map keys to values, making lookups nearly instant (O(1) complexity). However, this also means keys must be immutable (e.g., strings, numbers, or tuples)

Let’s see these operations in action with an example: 

# Creating a dictionary
person = {'name': 'Jay', 'age': 25, 'city': 'New Delhi'}

# Adding or Updating elements
person['age'] = 26  # Updating the age
person['job'] = 'Engineer'  # Adding a new key-value pair

# Removing elements
removed_value = person.pop('city')  # Removing the key 'city'
random_item = person.popitem()  # Removing and returning a random key-value pair

# Accessing values
name = person['name']  # Accessing the value associated with the key 'name'

# Keys, values, and items
keys = person.keys()  # Getting all keys
values = person.values()  # Getting all values
items = person.items()  # Getting all key-value pairs

Output: 

person = {'name': 'Jay', 'age': 26, 'job': 'Engineer'}
removed_value = 'New Delhi'
random_item = ('job', 'Engineer')
name = 'Jay'
keys = dict_keys(['name', 'age', 'job'])
values = dict_values(['John', 26, 'Engineer'])
items = dict_items([('name', 'Jay'), ('age', 26), ('job', 'Engineer')])

Explanation:

  • Adding or Updating elements:
    • person['age'] = 26 updates the value associated with the key 'age'.
    • person['job'] = 'Engineer' adds a new key-value pair to the dictionary.
  • Removing elements:
    • pop('city') removes and returns the value associated with the key 'city'.
    • popitem() removes and returns a random key-value pair from the dictionary.
  • Accessing values:
    • person['name'] retrieves the value associated with the key 'name' (in this case, 'John').
  • Keys, values, and items:
    • person.keys() returns a view of all the keys in the dictionary.
    • person.values() returns a view of all the values in the dictionary.
    • person.items() returns a view of all key-value pairs in the dictionary.

Edge Cases to Consider

While dictionaries are very useful, there are some important edge cases to keep in mind:

  • KeyError: If you try to access a key that doesn’t exist in the dictionary, a KeyError will be raised.

Example: 

person = {'name': 'Jay', 'age': 26}
print(person['address'])  # This will raise a KeyError
  • Mutable Values: You can store mutable objects (like lists or dictionaries) as values in a dictionary. However, be cautious when modifying mutable values, as this may affect your data unintentionally.

Example: 

person = {'name': 'Jay', 'hobbies': ['reading', 'swimming']}
person['hobbies'].append('coding')  # This modifies the list directly
  • Overwriting Values: If you assign a new value to an existing key, it will overwrite the previous value associated with that key.

Example: 

person = {'name': 'Jay', 'age': 25}
person['age'] = 26  # This overwrites the value of 'age'

Also Read: A Complete Python Cheat Sheet (Updated 2024)

Next, let’s break down these types of data structures in Python across several factors, helping you choose the right one based on your specific use case.

Comparison of Data Structures in Python

When working with data in Python, understanding the strengths and weaknesses of each data structure can significantly impact the efficiency and clarity of your code. 

Let’s compare the types of data structures in Python based on the following factors:

Factor

List

Tuple

Set

Dictionary

Mutability Mutable (can be modified) Immutable (cannot be modified) Mutable (can be modified) Mutable (can be modified)
Storage of Duplicate Values Can store duplicates Can store duplicates Does not allow duplicates Can store duplicates in values, not keys
Order Preservation Ordered (from Python 3.7 onwards) Ordered (from Python 3.7 onwards) Unordered Ordered (from Python 3.7 onwards)
Access Time O(1) for indexing O(1) for indexing O(1) for membership test (in) O(1) for key lookup
Memory Usage Higher memory usage Lower memory usage Memory-efficient due to unique elements Higher memory usage due to key-value pairs
Ease of Use Easy to use for simple tasks Easy for fixed collections Ideal for uniqueness checks Ideal for mapping data, easy key-value access
Search Performance O(n) O(n) O(1) (average for lookups) O(1) for key lookup
Common Use Cases Storing ordered, mutable collections Storing immutable, ordered data Ensuring uniqueness in collections Storing key-value pairs, fast lookups

To further enhance your Python skills, upGrad offers tailored programs designed to take your expertise to the next level.

How upGrad Advances Your Expertise in Python Programming?

upGrad offers comprehensive courses that deepen your knowledge of Python, covering everything from basic syntax to advanced topics like algorithms and data structures. With expert mentorship, hands-on projects, and personalized feedback, upGrad ensures you gain practical experience and build real-world applications. 

Here are some of the top courses you can check out: 

Start with upGrad's free courses to build a solid Python foundation, and unlock advanced opportunities in data science and AI.

For personalized career guidance, consult upGrad’s expert counselors or visit our offline centers to find the best course tailored to your goals.

Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!

Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!

Stay informed and inspired  with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!

Frequently Asked Questions

1. What are the types of data structures in Python?

2. How do I choose between a list and a tuple in Python?

3. Can a set store duplicate values?

4. How do you access elements in a Python list?

5. How do Python dictionaries handle collisions in hashing?

6. When should I use a tuple instead of a list?

7. What is the significance of immutability in a tuple?

8. Why are sets faster for lookups than lists?

9. How do sets handle ordering?

10. How do I loop through a dictionary in Python?

11. Can I use a list of lists in Python?

Rohit Sharma

711 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

18 Months

upGrad Logo

Certification

3 Months