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

Difference Between List and Tuple in Python

Updated on 22/01/202514,022 Views

In Python, List and Tuples are built-in data structures for storing and managing the collections of data. A list is like a flexible notebook where you can add, remove, or rearrange items. On the other hand, a tuple is like a sealed envelope — once packed, its contents remain unchanged. While they might look similar, the differences between list and tuple are really important for how you’ll use them in your programs.

It can be a bit tricky to know when to use a list or a tuple. Many developers find themselves mixing them up, which can lead to slower code, unexpected bugs, or even wasted resources. This confusion usually stems from not fully knowing their unique features and the best scenarios to use them in.

But don’t worry! It’s actually pretty easy to sort this out. By learning about key distinctions like mutability, performance, and use cases, you'll be able to confidently decide when to use each one.

In this article, we will explore what is list, what is tuple and the key difference between tuple and list in Python with the help of examples. Whether you’re just starting with Python or looking to sharpen your skills, this guide will help you write smarter and more efficient code. Happy coding!

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

What is List in Python?

A list in Python is a built-in data structure that enables you to store a collection of items. These items can vary in data types, including integers, strings, or even other lists.

Lists are among the most versatile and frequently used data structures in Python because they are mutable, which means you can modify their contents after they've been created.

Key Features of Lists

  1. Ordered: The elements in a list maintain the order in which they were added.
  2. Mutable: After a list is created, you can add, remove, or modify its elements.
  3. Heterogeneous: Lists can contain elements of various data types. Indexable: You can access elements by their index, starting from 0.
  4. Dynamic Size: Lists can grow or shrink as needed, unlike arrays in some programming languages.

Syntax of a Python List

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

Operations on Lists

  1. append(): Adds a single element to the end of the list.
  2. extend(): Adds multiple elements to the end of the list.
  3. insert(index, element): Adds an element at a specified position.
  4. remove(): Removes the first occurrence of a value.
  5. pop(index): Removes and returns the element at a specified index.
  6. clear(): Removes all elements from the list.
  7. count(): Returns the number of occurrences of an element.
  8. sort(): Sorts the elements in ascending order.
  9. reverse(): Reverses the order of the elements in the list.
  10. index(): Returns the index of the first occurrence of a value.

Also Read: Lists Methods in Python

What is Tuple in Python?

A tuple in Python is an ordered and immutable collection of elements. It is similar to a list, but unlike lists, tuples cannot be modified after they are created.

Tuples are defined using parentheses () and can hold elements of various data types, including integers, strings, floats, and even other collections.

Key Features of Tuples in Python

  1. Ordered: The elements in a tuple maintain their order.
  2. Immutable: Once created, the contents of a tuple cannot be modified; this means you cannot add, remove, or change elements.
  3. Heterogeneous: Tuples can store elements of different data types.
  4. Indexable: You can access elements using their index, which starts at 0.
  5. Faster than Lists: Operations on tuples are generally faster than on lists because of their immutability.
  6. Hashable: Tuples can be used as keys in dictionaries, provided they contain hashable elements.

Syntax of a Python Tuple

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

Operations on Tuple

  1. index(value): Returns the first index of the specified value.
  2. count(value): Returns the number of occurrences of the specified value.
  3. len(): Returns the total number of elements in the tuple.
  4. tuple(sequence): Converts a sequence (like a list or string) into a tuple.
  5. in (Membership Test): Checks if an element exists in the tuple.
  6. + (Concatenation): Combines two or more tuples.
  7. * (Repetition): Repeats the elements in a tuple.

“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!”

Difference Between List and Tuple in Python

Parameter

List

Tuple

Definition

A list is an ordered, mutable collection of items.

A tuple is an ordered, immutable collection of items.

Syntax

Defined using square brackets [ ].

Defined using parentheses ( ) .

Mutability

Mutable: Elements can be added, removed, or modified.

Immutable: Elements cannot be changed once the tuple is created.

Performance

Slower due to dynamic resizing and mutability.

Faster due to immutability and smaller memory footprint.

Memory Usage

Consumes more memory as it supports additional functionalities like append or pop.

Consumes less memory as it has fewer functionalities.

Methods Available

Provides methods like append(), remove(), sort(), etc.

Limited methods like count() and index().

Use Case

Suitable for dynamic collections where data changes frequently.

Ideal for fixed data that does not require modification.

Iteration Speed

Slower than tuples during iteration.

Faster due to immutability and reduced overhead.

Error Safety

More prone to accidental changes or bugs.

Safer as the data remains constant throughout the program.

Nesting Capability

Can nest lists, tuples, or other collections.

Can also nest tuples or other collections.

Type Conversion

A list can be converted to a tuple using tuple().

A tuple can be converted to a list using list().

Similarities Between Tuple and List

  1. Ordered: Both lists and tuples keep the order of their elements.
  2. Indexing: Both data structures support indexing and slicing for accessing specific elements.
  3. Heterogeneous Elements: Both can store elements of different data types.
  4. Nesting: Both allow for the nesting of other lists or tuples within them.
  5. Iterability: Both are iterable, making them suitable for loops and comprehensions.

List vs Tuple: When to Use

  1. Dynamic Operations: Use lists for tasks that require frequent addition, deletion, or updates of elements.
  2. Fixed Data: Choose tuples when you need data that should remain unchanged throughout the program.
  3. Memory Constraints: Opt for tuples if you need to perform memory-efficient operations.
  4. Iterative Processes: Tuples are more suitable for loops that require high-speed iterations.
  5. Error Prevention: Use tuples to prevent accidental modification of critical data.

Tuple vs List: Examples of List and Tuple

Python List Example

Let’s create an employee dataset, and then perform different operations of list on that.

# Dataset of employee details with Indian names

employee_data = [
    {"Name": "Aditi", "Department": "HR"},
    {"Name": "Rahul", "Department": "IT"},
    {"Name": "Sneha", "Department": "Finance"}
]
# Extracting employee names into a list
employee_names = [employee["Name"] for employee in employee_data]
# Printing the list of names
print("List of Employee Names:", employee_names)

Output

List of Employee Names: ['Aditi', 'Rahul', 'Sneha']

Now, let’s perform different Python list operations

# List of employee names (extracted from the dataset)

employee_names = ['Aditi', 'Rahul', 'Sneha']
# Accessing elements in the list
print("First Employee:", employee_names[0])  # Access the first element
print("Last Employee:", employee_names[-1])  # Access the last element
# Adding a new employee to the list
employee_names.append('Ankit')
print("Updated List of Employees:", employee_names)
# Removing an employee from the list
employee_names.remove('Rahul')
print("After Removing Rahul:", employee_names)
# Iterating through the list
print("Employee Names:")
for name in employee_names:
    print(name)
# Checking if an employee exists in the list
if 'Sneha' in employee_names:
    print("Sneha is in the list.")
else:
    print("Sneha is not in the list.")

Output

First Employee: Aditi
Last Employee: Sneha
Updated List of Employees: ['Aditi', 'Rahul', 'Sneha', 'Ankit']
After Removing Rahul: ['Aditi', 'Sneha', 'Ankit']
Employee Names:
Aditi
Sneha
Ankit
Sneha is in the list.

Python Tuple Example

Here, we will do same. First we will create a dataset and then perform operations on tuple.

# Tuple of city weather data

weather_data = (
    ("Mumbai", 32, 75),
    ("Delhi", 38, 50),
    ("Chennai", 34, 80),
    ("Kolkata", 30, 85),
)
# Access weather data for Mumbai
mumbai_weather = weather_data[0]
print("Weather data for Mumbai:", mumbai_weather)
# Display weather data for all cities
for city, temperature, humidity in weather_data:
    print(f"City: {city}, Temperature: {temperature}°C, Humidity: {humidity}%")
# Find the city with the highest temperature
hottest_city = max(weather_data, key=lambda x: x[1])
print("Hottest city:", hottest_city[0])    
# Convert the tuple to a list to add new city data
weather_data_list = list(weather_data)
weather_data_list.append(("Bengaluru", 28, 70))
weather_data = tuple(weather_data_list)  # Convert back to a tuple
print("Updated weather data:", weather_data)

Output

Weather data for Mumbai: ('Mumbai', 32, 75)
City: Mumbai, Temperature: 32°C, Humidity: 75%
City: Delhi, Temperature: 38°C, Humidity: 50%
City: Chennai, Temperature: 34°C, Humidity: 80%
City: Kolkata, Temperature: 30°C, Humidity: 85%
Hottest city: Delhi
Updated weather data: (('Mumbai', 32, 75), ('Delhi', 38, 50), ('Chennai', 34, 80), ('Kolkata', 30, 85), ('Bengaluru', 28, 70))

Applications of Lists and Tuple in Python

Application of Lists in Python

  1. Dynamic Data Storage: Lists are ideal for storing data that may change during the program's execution.
  2. Data Manipulation: Lists support operations like adding, removing, and sorting data, making them perfect for dynamic datasets.
  3. Implementation of Stacks and Queues: Lists can act as stacks (LIFO) and queues (FIFO) using append() and pop() methods.
  4. Iteration and Filtering: Lists can store large datasets for processing and filtering.
  5. Graph and Matrix Representation: Lists are often used to represent graphs, adjacency matrices, or 2D grids.

Application of Tuple in Python

  1. Read-Only Data: Tuples are ideal for storing constant data that shouldn’t be modified.
  2. Function Return Values: Tuples are commonly used to return multiple values from a function.
  3. Keys in Dictionaries: Tuples, being immutable, can be used as keys in dictionaries.
  4. Immutable Data Grouping: Tuples are perfect for grouping related but unchangeable data.
  5. Memory-Efficient Collections: Tuples consume less memory than lists, making them suitable for large, read-only datasets.
  6. Data Interchange (Serialization): Tuples are used in cases like data interchange where immutability is required (e.g., passing data between threads).

How upGrad can Help you?

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

FAQ’s

What is the difference between List and Tuple in Python?

  • Mutability: Lists are mutable, which means their elements can be changed after creation. Tuples are immutable; once defined, their elements cannot be altered.
  • Syntax: Lists are defined using square brackets [], while tuples use parentheses ().
  • Performance: Due to their immutability, tuples can be more memory-efficient and faster than lists, especially when iterating over large sequences.
  • Use Cases: Lists are suitable for collections of items that may change during program execution, such as elements that need to be added, removed, or modified. Tuples are ideal for fixed collections of items, like coordinates or other data that should remain constant.

Is tuple or list better?

The choice between a list and a tuple depends on your program's specific needs:

  • Use a list when: You need a mutable sequence that allows modifications, such as adding, removing, or changing elements.
  • Use a tuple when: You require an immutable sequence to ensure that the data remains constant throughout the program.

Why are tuples immutable?

Tuples are designed to be immutable to provide data integrity and allow for optimizations:

  • Data Integrity: Immutability ensures that the data cannot be altered accidentally, which is crucial for fixed collections of items.
  • Performance: Immutability allows Python to make internal optimizations, leading to potential performance improvements in terms of speed and memory usage.

Can tuples have duplicates?

Yes, tuples can contain duplicate elements.

Can two tuples be merged?

Yes, you can concatenate two tuples using the + operator.

What is the difference between del and remove() on lists?

  • remove() method: Removes the first occurrence of a specified value from the list.
  • del statement: Deletes an item at a specific index or slices the list to remove multiple items.

How do I change a list to a tuple?

You can convert a list to a tuple using the tuple() constructor.

Which is faster, list or tuple in Python?

Generally, tuples can be slightly faster than lists due to their immutability, which allows for optimizations. However, the performance difference is usually minimal and should not be the sole factor in choosing between them.

How to create a tuple?

Tuples can be created by placing comma-separated values within parentheses

What is mutable and immutable in Python?

  • Mutable Objects: Objects whose state or content can be changed after creation. Examples include lists, dictionaries, and sets.
  • Immutable Objects: Objects whose state or content cannot be changed once created. Examples include tuples, strings, and integers.

Ready to challenge yourself? Take our Free Python Quiz!

image
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.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.