For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
In Python, lists, sets, tuples, and dictionaries are essential data structures used to store and manage data. A list is an ordered collection, a tuple is similar but immutable, a set is unordered with no duplicates, and a dictionary stores data in key-value pairs.
Understanding the differences between list, tuple, set, dictionary in Python with examples can be confusing, especially for beginners. You may wonder when to use each and how they differ in performance and functionality.
This tutorial will break down list, tuple, set, dictionary in python with examples, highlighting their key differences, including the probable confusing difference between list and tuple in Python. By the end, you’ll know exactly when and how to use each of them in your code.
Keep reading to learn how mastering these data structures will make your Python programming smoother, more efficient, and flexible!
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
A list in Python is an ordered collection of items, which means the elements in a list are stored in a specific order. You can store different data types in a list, such as strings, integers, or even other lists.
Lists are very versatile and are used frequently in Python programming.
Also Read: What Is Mutable And Immutable In Python?
To create a list in Python, you simply use square brackets [] and separate elements with commas:
my_list = [element1, element2, element3, element4, element5]
There are many operations you can perform on lists. Here are a few common ones:
Ready to take your coding skills to the next level? Explore upGrad’s Online Software Development Courses and start building the software solutions of tomorrow. Let's get coding today!
Also Read: List vs Tuple: Understanding the Differences in Python
A tuple in Python is similar to a list, but it’s immutable. The difference between list and tuple in python is that once you create a tuple, you cannot change its values. Tuples are ordered collections, meaning the items maintain their order.
They can hold multiple data types and are commonly used when you need a collection that should not be modified.
To create a tuple, you use parentheses () with items separated by commas:
my_tuple = (element1, element2, element3)
Here are common operations you can perform on tuples:
Also Read: What is Tuple in DBMS? Types, Examples & How to Work
A set in Python is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow duplicate values, and they don’t maintain the order of elements. Sets are commonly used when you need to store unique items and perform set operations like unions, intersections, and differences.
To create a set, you use curly braces {} or the set() function:
my_set = {element1, element2, element3}
You can also create an empty set using set():
empty_set = set()
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
A dictionary in Python is an unordered collection of data stored in key-value pairs. In simpler terms, it's like a real-world dictionary where each word (key) has a definition (value).
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
A comma separates each key-value pair.
Some important operations include:
Want to level up your coding skills? Dive into upGrad’s Data Structures & Algorithms Course, master the essentials, and solve complex problems with ease. Start your journey now!
Now that you have a basic understanding let’s compare them.
Parameter | List | Tuple | Set | Dictionary |
Ordered | Yes | Yes | No | Yes |
Mutable | Yes | No | Yes | Yes |
Duplicates Allowed | Yes | No | No | Yes |
Indexing | Yes | Yes | No | Yes |
Data Types | Can store any data type | Can store any data type | Can store any immutable data type | Stores key-value pairs (any data type) |
Performance | Slower for large data sets | Faster for large data sets | Fast membership tests | Fast for key-based access |
Syntax | [ ] | ( ) | { } | {key: value} |
Use Cases | Ordered collections, collections to modify | Fixed data, protection from changes | Unique items, set operations | Mapping unique keys to values |
Supports Operations | Add, remove, sort, slice | Slice, count, index | Add, remove, union, intersection | Add, remove, update, access by key |
Examples | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {"a": 1, "b": 2} |
Let’s look at similarities next.
Also Read: Top 10 Python String Methods [With Examples]
Let’s look at list, tuple, set, dictionary in Python with examples.
In this example, you’ll work with a dataset of employees in a company.
Let’s first create a dictionary that contains employee names and their corresponding employee IDs.
employees = [
{"Name": "Rahul", "Department": "IT"},
{"Name": "Priya", "Department": "HR"},
{"Name": "Amit", "Department": "Finance"},
{"Name": "Neha", "Department": "IT"}
]
Now, let’s extract just the employee names into a list:
employee_names = [employee["Name"] for employee in employees]
This line creates a new list called ‘employee_names’ that contains only the names of the employees by looping through the employees list and accessing the Name field.
Let’s print the list of employee names:
print(employee_names)
Output:
['Rahul', 'Priya', 'Amit', 'Neha']
Now, let’s perform some common list operations on our employee_names list.
# access the name of the second employee in the list
second_employee = employee_names[1]
print(second_employee)
Output:
Priya
The list is zero-indexed, so employee_names[1] refers to the second element in the list, which is "Priya".
# add a new employee to the list
employee_names.append("Suresh")
print(employee_names)
Output:
['Rahul', 'Priya', 'Amit', 'Neha', 'Suresh']
We use append() to add "Suresh" to the end of the employee_names list.
# remove "Amit" from the list
employee_names.remove("Amit")
print(employee_names)
Output:
['Rahul', 'Priya', 'Neha', 'Suresh']
The remove() method removes the first occurrence of the specified element, in this case, "Amit".
# check if "Neha" is in the list
is_neha_present = "Neha" in employee_names
print(is_neha_present)
Output:
True
The “in” keyword checks if the element "Neha" is present in the list. The result is True because "Neha" is indeed in the list.
Let’s first create a tuple to store student names along with their grades:
students_grades = (
("Rahul", 85),
("Priya", 90),
("Amit", 78),
("Neha", 92)
)
Suppose you want to access Amit’s grade:
amit_grade = students_grades[2][1]
print(amit_grade)
Output:
78
The first index students_grades[2] gets the tuple ("Amit", 78), and then [1] accesses Amit’s grade.
count_90 = sum(1 for student in students_grades if student[1] == 90)
print(count_90)
Output:
1
The sum() function counts how many times 90 appears in the grades of the students.
first_two_grades = students_grades[:2]
print(first_two_grades)
Output:
[('Rahul', 85), ('Priya', 90)]
This slices the first two student-grade tuples from the original students_grades tuple.
# returns the index of the first occurrence of a specified value
index_of_priya = students_grades.index(("Priya", 90))
print(index_of_priya)
Output:
1
# counts how many times a value appears in the tuple
grade_count = students_grades.count(("Neha", 92))
print(grade_count)
Output:
1
# combines two tuples into one
additional_students = (("John", 88), ("Maya", 95))
all_students = students_grades + additional_students
print(all_students)
Output:
[('Rahul', 85), ('Priya', 90), ('Amit', 78), ('Neha', 92), ('John', 88), ('Maya', 95)]
# repeats a tuple a specified number of times
repeated_grades = students_grades * 2
print(repeated_grades)
Output:
[('Rahul', 85), ('Priya', 90), ('Amit', 78), ('Neha', 92), ('Rahul', 85), ('Priya', 90), ('Amit', 78), ('Neha', 92)]
# extracts a subset of the tuple
subset = students_grades[1:3]
print(subset)
Output:
[('Priya', 90), ('Amit', 78)]
Let’s first create a set with unique product IDs:
store_products = {101, 102, 103, 104, 105}
Here, we’ve used curly braces {} to define a set of product IDs. Since sets don’t allow duplicates, if you try adding a duplicate value, it will be ignored.
Let’s say a new product with ID 106 arrives in the store:
store_products.add(106)
print(store_products)
Output:
{101, 102, 103, 104, 105, 106}
The add() method adds the product ID 106 to the set.
Now, let’s say product with ID 102 is discontinued and needs to be removed:
store_products.remove(102)
print(store_products)
Output:
{101, 103, 104, 105, 106}
The remove() method removes the specified element, in this case, 102. If the item doesn’t exist, it will raise an error.
Let’s check if product 104 is available:
is_product_available = 104 in store_products
print(is_product_available)
Output:
True
The in operator checks whether 104 is in the set and returns True if it exists.
Here are some important set operations that you can perform in Python:
# combines two sets and returns a new set with all unique elements from both sets
other_products = {107, 108, 109}
all_products = store_products | other_products
print(all_products)
Output:
{101, 103, 104, 105, 106, 107, 108, 109}
# returns a set of elements that are common to both sets
discontinued_products = {102, 103, 106}
common_products = store_products & discontinued_products
print(common_products)
Output:
{103, 106}
# returns a set of elements that are in one set but not in the other
remaining_products = store_products - discontinued_products
print(remaining_products)
Output:
{101, 104, 105}
# returns a set of elements that are in one set or the other, but not in both
unique_products = store_products ^ discontinued_products
print(unique_products)
Output:
{101, 104, 105, 102}
# checks if one set is a subset of another (i.e. if all elements in the first set are also in the second)
smaller_set = {103, 106}
is_subset = smaller_set <= store_products
print(is_subset)
Output:
True
# removes all elements from the set
store_products.clear()
print(store_products)
Output:
set()
Also Read: Difference Between Function and Method in Python
Let’s create a dictionary to store book titles and authors:
library_books = {
"The Alchemist": "Paulo Coelho",
"1984": "George Orwell",
"To Kill a Mockingbird": "Harper Lee",
"Pride and Prejudice": "Jane Austen"
}
Let’s say you want to add a new book to the library:
library_books["The Catcher in the Rye"] = "J.D. Salinger"
print(library_books)
Output:
{'The Alchemist': 'Paulo Coelho', '1984': 'George Orwell', 'To Kill a Mockingbird': 'Harper Lee', 'Pride and Prejudice': 'Jane Austen', 'The Catcher in the Rye': 'J.D. Salinger'}
Let’s remove "1984" from the library:
del library_books["1984"]
print(library_books)
Output:
{'The Alchemist': 'Paulo Coelho', 'To Kill a Mockingbird': 'Harper Lee', 'Pride and Prejudice': 'Jane Austen', 'The Catcher in the Rye': 'J.D. Salinger'}
If you want to update the author of "The Alchemist":
library_books["The Alchemist"] = "Paulo Coelho (Revised)"
print(library_books)
Output:
{'The Alchemist': 'Paulo Coelho (Revised)', 'To Kill a Mockingbird': 'Harper Lee', 'Pride and Prejudice': 'Jane Austen', 'The Catcher in the Rye': 'J.D. Salinger'}
Let’s check if "Pride and Prejudice" exists in the library:
is_book_present = "Pride and Prejudice" in library_books
print(is_book_present)
Output:
True
The “in” operator checks if "Pride and Prejudice" is a key in the dictionary and returns True since it exists.
Here are some important dictionary operations you can perform in Python:
# retrieves the value associated with a given key
author = library_books.get("1984", "Not Found")
print(author)
Output:
Not Found
# returns a view object of all keys in the dictionary
keys = library_books.keys()
print(keys)
Output:
dict_keys(['The Alchemist', 'To Kill a Mockingbird', 'Pride and Prejudice', 'The Catcher in the Rye'])
# returns a view object of all values in the dictionary
values = library_books.values()
print(values)
Output:
dict_values(['Paulo Coelho (Revised)', 'Harper Lee', 'Jane Austen', 'J.D. Salinger'])
# returns a view object of all key-value pairs in the dictionary
items = library_books.items()
print(items)
Output:
dict_items([('The Alchemist', 'Paulo Coelho (Revised)'), ('To Kill a Mockingbird', 'Harper Lee'), ('Pride and Prejudice', 'Jane Austen'), ('The Catcher in the Rye', 'J.D. Salinger')])
# removes a key-value pair and returns the value
removed_book = library_books.pop("Pride and Prejudice")
print(removed_book)
print(library_books)
Output:
Jane Austen{'The Alchemist': 'Paulo Coelho (Revised)', 'To Kill a Mockingbird': 'Harper Lee', 'The Catcher in the Rye': 'J.D. Salinger'}
# removes all items from the dictionary
library_books.clear()
print(library_books)
Output:
{}
These were the list, tuple, set, dictionary in Python with example, showcasing how each data structure can be used in different scenarios.
To learn more about data structures, OOPs, etc., join upGrad’s Programming with Python: Introduction for Beginners course and kickstart your programming journey!
Let’s take a look at some common use cases where lists shine and how they differ from other data structures.
Also Read: Attributes in DBMS: Types of Attributes in DBMS
Tuples are widely used when you need a fixed collection of items. Here are some practical applications of tuples:
Also Read: How to Take Multiple Input in Python: Techniques and Best Practices
Sets in Python are used when you need to store unique items. Here are some common use cases:
Dictionaries in Python are handy for mapping unique keys to values. Here are some common use cases:
Also Read: 12 Amazing Real-World Applications of Python
Understanding the difference between list, tuple, set, dictionary in Python with example will help you make the right choice for your project.
With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Python courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.
By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.
So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.
Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:
Similar Reads: Top Trending Blogs of Python
No, tuples are immutable, meaning once created, you cannot modify their elements.
The main difference is that lists are mutable (can be changed), while tuples are immutable (cannot be changed).
Yes, sets can store immutable different data types, but they cannot store mutable types like lists or dictionaries.
Duplicate values are automatically removed when you add them to a set. Sets only store unique values.
No, dictionary keys must be unique. If you try to add a duplicate key, it will overwrite the previous value.
Use a dictionary when you need to map data using unique keys, like associating student IDs with names or product IDs with prices.
No, only sets support mathematical operations like union and intersection directly. Lists require other methods for these operations.
Lists maintain the order of elements, while sets are unordered collections, meaning the elements are not stored in any specific order.
Yes, dictionaries can store lists as values, allowing you to map keys to more complex data types like lists or other dictionaries.
Lists and tuples are slower for membership tests compared to sets, which are optimized for quick lookups. Tuples are more memory-efficient than lists.
Yes, since tuples are immutable, they can be used as dictionary keys, unlike lists, which are mutable and cannot be used as keys.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.