1. Home
python

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

  • 201 Lessons
  • 33 Hours
right-top-arrow

Tutorial Playlist

200 Lessons
39

Difference Between List, Tuple, Set, and Dictionary in Python

Updated on 22/05/20245,774 Views

Introduction

Python, being a flexible language, offers multiple data structures to store and manage data. Understanding the unique characteristics and use cases of each structure is pivotal for effective programming. In this tutorial, we will delve deep into the fundamental difference between dictionary, list, tuple and set in Python four of Python’s primary data structures.

Overview

Python is rich with in-built data structures, making data manipulation and storage convenient. Among these, list, tuple, set, and dictionary stand out due to their ubiquity in various applications. These structures differ based on factors like mutability, order preservation, and element uniqueness. Let's unpack the intricacies of the difference between dictionary, list, tuple and set in Python.

What is a List in Python?

A list is a widely used versatile data structure that allows you to store a collection of items. Lists are ordered, mutable (modifiable), and can contain elements of different data types, such as strings, integers, floats, and even other lists. Lists are defined by enclosing a comma-separated sequence of elements within square brackets []. You can access, modify, and perform various operations on the elements of a list.

Here is the syntax for lists:

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

In the above syntax,

  • my_list: This is the name of the list variable that you choose.
  • [element1, element2, element3, ...]: These are the elements you want to store in the list, separated by commas and enclosed in square brackets.

Here is an example Python program that will demonstrate the creation and manipulation of lists:

# Create a list of integers
numbers = [1, 2, 3, 4, 5]

# Access and print elements of the list
print("The first element is:", numbers[0])
print("The third element is:", numbers[2])

# Modify an element of the list
numbers[1] = 10

# Add an element to the end of the list
numbers.append(6)

# Remove an element from the list
numbers.remove(3)

# Find the length of the list
length = len(numbers)

# Check if an element is in the list
if 4 in numbers:
    print("4 is in the list")

# Iterate through the list
print("List elements:")
for num in numbers:
    print(num)

# Sort the list in ascending order
numbers.sort()

# Reverse the list
numbers.reverse()

# Create a list of mixed data types
mixed_list = [1, "apple", 3.14, True]

# Nested lists (lists within a list)
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Access elements of a nested list
print("Element at row 2, column 3:", nested_list[1][2])

The above code begins by creating a list named numbers using the list data structure in Python, with the syntax:

numbers = [1, 2, 3, 4, 5]

This list contains five integer elements. Subsequently, the code showcases various list operations, including element access and modification using index positions (e.g., numbers[0] accesses the first element), appending elements to the list using the append() method, removing elements by value with the remove() method, finding the length of the list using the len() function, checking for the presence of an element using the in operator, and iterating through the list using a for loop.

It also demonstrates list sorting and reversing using the sort() and reverse() methods. Furthermore, the code defines a nested list called nested_list, which contains three inner lists.

Finally, it shows how to access an element within the nested list with the syntax:

Nested_list[1][2]

This accesses the element at row 2, column 3, which is 6.

What is a Tuple in Python?

A tuple is an ordered and immutable (unchangeable) collection of elements. Tuples are defined by enclosing a comma-separated sequence of elements within parentheses (). Like lists, tuples can store elements of different data types. However, once a tuple is created, you cannot modify its contents. Tuples are often used when you want to ensure the data remains constant or unchangeable.

Here is the syntax for tuples:

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

In the above syntax,

  • my_tuple: This is the name of the tuple variable.
  • (element1, element2, element3, ...): These are the elements enclosed in parentheses and separated by commas.

Here is an example Python program that will demonstrate the creation of tuples and some common operations on tuples:

# Create a tuple of mixed data types
my_tuple = (1, "apple", 3.14, True)

# Access elements of the tuple using indexing
print("The first element is:", my_tuple[0])
print("The second element is:", my_tuple[1])

# Attempting to modify a tuple will result in an error
# Uncommenting the line below will cause an error
# my_tuple[0] = 10

# Find the length of the tuple
length = len(my_tuple)

# Check if an element is in the tuple
if 3.14 in my_tuple:
    print("3.14 is in the tuple")

# Iterate through the tuple
print("Tuple elements:")
for item in my_tuple:
    print(item)

# Concatenate tuples
tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")
concatenated_tuple = tuple1 + tuple2

# Repeat a tuple
repeated_tuple = tuple1 * 3

# Nested tuples
nested_tuple = ((1, 2), (3, 4), (5, 6))

# Access elements of a nested tuple
print("Element at row 2, column 1:", nested_tuple[1][0])

The above program begins by creating a tuple named my_tuple and accesses the elements of the tuple using index positions. The first element (1) is accessed with my_tuple[0], and the second element ("apple") is accessed with my_tuple[1].

The code also calculates the length of the tuple, checks for the presence of an element, and iterates through the tuple using a for loop. The len() function is used to find and store the length of the my_tuple tuple.

What is a Set in Python?

A set is an unordered collection of unique elements. Sets are defined by enclosing a comma-separated sequence of elements within curly braces {} or by using the set() constructor. Sets are primarily used for tasks that involve storing and manipulating a collection of distinct values.

Here is the syntax for creating sets:

my_set = {element1, element2, element3, ...}
# OR
my_set = set([element1, element2, element3, ...])

In the above syntax,

  • my_set: This is the name of the set variable.
  • {element1, element2, element3, ...}: These are the elements.

Here is an example of working with sets in Python:

# Create a set of unique integers
my_set = {1, 2, 3, 4, 5}

# Attempting to add a duplicate element will have no effect
my_set.add(2)

# Remove an element from the set
my_set.remove(3)

# Check if an element is in the set
if 4 in my_set:
    print("4 is in the set")

# Find the length of the set
length = len(my_set)

# Iterate through the set
print("Set elements:")
for item in my_set:
    print(item)

# Perform set operations (union, intersection, difference)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2

# Convert a list to a set to remove duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)

What is a Dictionary in Python?

Dictionaries are unordered collections of key-value pairs. Each key in a dictionary is unique, and it is associated with a corresponding value. A dictionary is defined by enclosing a comma-separated sequence of key-value pairs within curly braces {}. They are used for efficient data retrieval and storage of key-associated values.

Here is the syntax for creating dictionaries:

my_dict = {key1: value1, key2: value2, key3: value3, ...}

In the above syntax,

  • my_dict: This is the name of the dictionary variable.
  • {key1: value1, key2: value2, key3: value3, ...}: These are the key-value pairs enclosed in curly braces and separated by commas.

Here is an example of using a dictionary in Python:

# Create a dictionary of key-value pairs
my_dict = {"name": "John", "age": 30, "city": "New York"}

# Access values using keys
name = my_dict["name"]
age = my_dict["age"]

# Attempting to access a non-existent key will raise a KeyError
# Uncommenting the line below will cause an error
# country = my_dict["country"]

# Check if a key is in the dictionary
if "city" in my_dict:
    print("City is in the dictionary")

# Find the number of key-value pairs in the dictionary
num_items = len(my_dict)

# Iterate through keys and values
print("Dictionary elements:")
for key, value in my_dict.items():
    print(key, ":", value)

# Modify a value associated with a key
my_dict["age"] = 31

# Add a new key-value pair to the dictionary
my_dict["country"] = "USA"

# Remove a key-value pair from the dictionary
del my_dict["city"]

Difference Between List, Tuple, Set, and Dictionary

Having grasped the fundamental attributes of Python's core data structures - list, tuple, set, and dictionary - it becomes imperative to discern their distinctive aspects. These nuances can greatly influence the choice of data structure for specific tasks.

1. Mutability

Mutability refers to the ability of an object to change its state or content after its creation.

  • List: Lists are mutable. This means that after defining a list, you can alter its content – be it changing, adding, or removing elements. The ability to modify lists makes them versatile, especially when you need a collection that will undergo various transformations during runtime.
  • Tuple: In stark contrast, tuples are immutable. Once created, their content remains static. This fixed nature makes tuples hashable and usable as dictionary keys. They're especially suitable when you need to ensure data integrity and ensure certain values remain constant throughout a program.
  • Set: Sets are mutable, allowing insertion and removal of elements. However, since they only house unique values, any attempt to add a duplicate value will be ignored. This makes them invaluable for tasks like deduplication.
  • Dictionary: These are mutable, granting you the flexibility to add, remove, or change key-value pairs. However, their keys, much like tuple elements, need to be of immutable types.

2. Ordering

Ordering relates to whether a data structure maintains a consistent sequence of its contained elements.

  • List: Lists are inherently ordered. The sequence in which you insert elements into a list is preserved, allowing indexed access and modifications. This characteristic is useful for tasks like sorting or when the sequence has semantic meaning, like storing monthly sales data.
  • Tuple: Tuples, like lists, are ordered. Even though they're immutable, the sequence they're declared in remains consistent.
  • Set: A set doesn't retain any specific order. It’s designed for membership tests, making it optimal for scenarios where insertion order isn't significant but ensuring uniqueness is.
  • Dictionary: In versions prior to Python 3.7, dictionaries didn't guarantee order. However, from Python 3.7 onwards, dictionaries maintain the order of items based on their insertion. This ensures a predictable mapping, beneficial for operations like serialization.

3. Duplicate Handling

How a data structure handles duplicates often determines its utility in particular scenarios.

  • List: Lists don't discriminate against duplicate values. They're accommodating structures that will store as many identical elements as you insert, which is handy for collections where occurrences matter.
  • Tuple: Tuples also permit duplicates, offering another avenue for ordered, immutable storage.
  • Set: Sets stand out by not allowing any duplicate values. This inherent property assists in creating collections of unique items, which can be beneficial for operations like union, intersection, and difference.
  • Dictionary: While dictionaries allow duplicate values, their keys must be unique. This ensures a one-to-one mapping between keys and values.

4. Data Structure Representation

Understanding how each structure is represented syntactically can accelerate coding speed and reduce errors.

  • List: Denoted by square brackets. e.g., [1, 2, 3]
  • Tuple: Encapsulated within parentheses. e.g., (1, 2, 3)
  • Set: Defined using curly brackets without key-value pairs. e.g., {1, 2, 3}
  • Dictionary: Illustrated using curly brackets with distinct key-value pairs. e.g., {'a':1, 'b':2, 'c':3}

For a streamlined understanding, consider the following table:

Aspect

list

tuple

set

dictionary

Mutable?

Yes

No

Yes

Yes

Ordered?

Yes

Yes

No

No

Allows Duplicates?

Yes

Yes

No

Yes (Values)

Unique Feature

-

Can be a dictionary key

Mathematical operations

Key-Value pairs

Representation

[1, 2, 3]

(1, 2, 3)

{1, 2, 3}

{'a':1, 'b':2, 'c':3}

When developing Python applications, this differentiation becomes pivotal. It ensures that the right structure is harnessed for the task, optimizing both performance and data integrity.

Conclusion

Navigating Python’s array of data structures effectively requires a nuanced understanding of their differences. Each structure – list, tuple, set, and dictionary – possesses unique characteristics catering to specific tasks. While their foundational principles are simple, mastering their applications can provide significant advantages in various programming challenges.

If you're keen on diving deeper into Python and exploring advanced topics, consider upGrad's specialized courses to further enhance your expertise.

FAQs

1. What's the main difference between tuple and set in Python?

tuples are ordered and immutable collections, usually denoted by (). In contrast, sets are unordered, mutable collections of unique elements, represented using {}.

2. What is the difference between tuple and dictionary in Python?

While both are collections, a dictionary is unique due to its key-value pair structure. tuples are ordered collections indexed by integer values.

3. Can you briefly describe the relationship between list, tuple, dictionary in Python?

All three are fundamental data structures in Python. lists and tuples store ordered collections, but tuples are immutable. Dictionaries are unordered key-value stores.

4. Is there a notable difference between set and dictionary in Python in terms of performance?

sets and dictionaries both utilize hashing, hence they offer O(1) average time complexity for lookups. The performance nuances arise based on operations and data specifics.

5. Why might one choose a tuple over a list or vice versa?

tuples are preferable when immutability is required, like for dictionary keys. lists, being mutable, are apt for dynamic, modifiable collections.

Pavan

PAVAN VADAPALLI

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working … Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...