Site icon Trafficbots

List vs Tuple in Python: Key Differences Explained with Examples

List vs Tuple in Python: Key Differences Explained with Examples

List vs Tuple in Python: Key Differences Explained with Examples

List and Tuple are used to store objects in Python. Although they appear similar at first glance, there are important differences in how they behave and when they should be used. Objects stored in both lists and tuples can be of any data type.

This article explains the difference between a list and a tuple in Python. By the end, you will clearly understand their syntax differences, available operations, performance characteristics, and ideal use cases.

Key Differences Between List and Tuple

The primary difference between lists and tuples is mutability:

Because of immutability, tuples:

If your data is fixed and should remain unchanged, tuples are usually a better choice than lists.

List vs Tuple: Feature Comparison

FeatureListTuple
MutabilityMutable (elements can be changed)Immutable (elements cannot be changed)
SyntaxSquare brackets [ ]Parentheses ( )
PerformanceSlower due to dynamic sizeFaster due to static size
MethodsMore built-in methods (append, remove, etc.)Fewer methods (count, index)
Use CasesSuitable for changing dataIdeal for fixed data
Memory UsageConsumes more memoryConsumes less memory
IterationSlightly slowerFaster
HashabilityNot hashableHashable (if elements are hashable)

What is a List in Python?

Lists are one of Python’s most flexible and powerful data structures. They are similar to arrays in other programming languages.

Features of Python Lists

Because lists are dynamic, they are ideal when the number of elements is not fixed.

List Syntax

A list is created using square brackets [ ].

num_list = [1, 2, 3, 4, 5]
print(num_list)

alphabets_list = ['a', 'b', 'c', 'd', 'e']
print(alphabets_list)

Mixed Data Types

mixed_list = ['a', 1, 'b', 2, 'c', 3, '4']
print(mixed_list)

Nested List

nested_list = [1, 2, 3, [4, 5, 6], 7, 8]
print(nested_list)

What is a Tuple in Python?

Tuples are also a sequence data type that can store elements of different data types. They are especially useful when you want the stored data to remain unchanged.

Features of Python Tuples

Tuple Syntax

A tuple is created using parentheses ( ).

num_tuple = (1, 2, 3, 4, 5)
print(num_tuple)

alphabets_tuple = ('a', 'b', 'c', 'd', 'e')
print(alphabets_tuple)

Mixed Data Types

mixed_tuple = ('a', 1, 'b', 2, 'c', 3, '4')
print(mixed_tuple)

Nested Tuple

nested_tuple = (1, 2, 3, (4, 5, 6), 7, 8)
print(nested_tuple)

Syntax Differences Between List and Tuple

Lists use square brackets, while tuples use round brackets.

list_numbers = [1, 2, 3, 4, 5]
tuple_numbers = (1, 2, 3, 4, 5)

print(list_numbers)
print(tuple_numbers)

You can verify the data type using the type() function:

type(list_numbers)
type(tuple_numbers)

Difference Between List and Tuple in Python (In-Depth)

Lists are mutable, meaning their elements can be changed after creation. Tuples are immutable, so their contents cannot be modified.

Attempting to modify a tuple results in an error:

names = ("Raj", "John", "Jabby", "Raja")
names[2] = "Kelly"

Error:

TypeError: 'tuple' object does not support item assignment

Tuples also have a fixed length throughout the program’s lifecycle, which contributes to their lower memory overhead.

Mutable Lists vs Immutable Tuples

Modifying a List

list_num = [1, 2, 3, 4, 5]
list_num[2] = 5
print(list_num)

Output:

[1, 2, 5, 4, 5]

Attempting to Modify a Tuple

tuple_num = (1, 2, 3, 4, 5)
tuple_num[2] = 7

Error:

TypeError: 'tuple' object does not support item assignment

Available Operations on Lists

Because lists are mutable, they support many built-in operations:

These operations allow lists to be modified easily and flexibly.

Available Operations on Tuples

Due to immutability, tuples support fewer operations:

Size Comparison: List vs Tuple

Tuples have a fixed size and lower memory overhead compared to lists.

a = (1,2,3,4,5,6,7,8,9,0)
b = [1,2,3,4,5,6,7,8,9,0]

print(a.__sizeof__())
print(b.__sizeof__())

Tuples are allocated larger contiguous memory blocks, while lists use dynamic memory allocation, making tuples faster for large datasets.

Different Use Cases

When to Use Lists

  1. When data needs to change frequently
  2. When performing mathematical operations on collections
  3. When the number of elements is unknown

When to Use Tuples

  1. When data should remain constant
  2. When using elements as dictionary keys
  3. When better performance and memory efficiency are required

Tuples as Dictionary Keys

Tuples are hashable and can be used as dictionary keys:

tuplekey = {}
tuplekey[('blue', 'sky')] = 'Good'
tuplekey[('red', 'blood')] = 'Bad'
print(tuplekey)

Tuple Packing and Unpacking

Tuple Packing

person = ("Rohan", "6 ft", "Employee")
print(person)

Tuple Unpacking

(name, height, profession) = person
print(name)
print(height)
print(profession)

When to Use Tuples Over Lists?

Tuples are best when:

Examples include storing a person’s birthdate, height, or credentials.

List vs Tuple: Which Is Better in Python?

In summary, lists offer flexibility, while tuples provide performance and safety.

Conclusion

Now that you understand the differences between lists and tuples in Python, you can confidently choose the right data structure for your needs. Lists are ideal for dynamic data, while tuples are best for fixed, immutable collections.

With this foundation, you are better prepared to explore advanced Python concepts and write more efficient, reliable code.

Exit mobile version