Difference Between Lists and Tuples in Python



List and Tuples are built-in data types of Python programming language. They serve as a container to hold multiple values of same type as well as different data types.

We can find several differences in both of these containers. Read this article to learn more about lists and tuples in Python and how they are different from each other.

List in Python

List is a container that contains different types of objects. In it, the elements are separated by commas and stored within square brackets. Each element of a list has a unique position index, starting from 0.

Example

The following example shows how to create, display and modify a list in Python.

# creating a list of characters
char_list = ['a', 'b', 'c', 'd', 'e']
print("Original list:", char_list)

# Modifying the list
char_list[0] = 10
char_list.append(5)
print("After modifying list:",char_list)

When you run this program, the following output will be displayed ?

Original list: ['a', 'b', 'c', 'd', 'e']
After modifying list: [10, 'b', 'c', 'd', 'e', 5]

Tuples in Python

Tuple is also similar to a list but it contains immutable objects and they are stored within parentheses. Those objects that cannot be modified by any means are called as immutable.

Example

In this example, we will create a tuple and try to modify it.

# creating a tuple of characters
char_tuples = ('a', 'b', 'c', 'd', 'e')
print("Original tuple:", char_tuples)

# Modifying the tuple
char_tuples[0] = 10
print("After modifying tuple:",char_tuples) 

On executing, the original tuple will be displayed along with an error message which specifies tuples elements could not be modified.

Original tuple: ('a', 'b', 'c', 'd', 'e')
Traceback (most recent call last):
  File "/home/cg/root/17243/main.py", line 6, in <module>
    char_tuples[0] = 10
TypeError: 'tuple' object does not support item assignment

Difference between List and Tuples

Following are the important differences between List and Tuple ?

Criteria List Tuple
Type List is mutable which means its elements can be updated as per requirement. Tuple is immutable which means we can't modify its element once created.
Iteration List iteration is slower and is time consuming. Tuple iteration is faster.
Appropriate for List is useful for insertion and deletion operations. Tuple is useful for read-only operations like accessing elements.
Memory Consumption List consumes more memory. Tuples consumes less memory.
Methods List provides many built-in methods. Tuples have less built-in methods as compare to list.
Error prone List operations are more error prone. Tuples operations are safe.
Updated on: 2024-07-30T16:43:11+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements