Both lists and tuples are used for storing objects in python. They seem similar, but there are specific differences in their use case. Objects that are stored in lists and tuples can be of any type. 

This article will explain the difference between list and tuple in python. By the end of this article, you will be adept in syntax difference, available operations, and scenarios of using lists and tuples in python.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

What Is a List in Python?

Lists are one of the most flexible and powerful containers in Python. It is similar to an array in other languages like Java. 

The list has the following features - 

  • You can use Python lists to store data of multiple types simultaneously.
  • Lists help preserve data sequences and further process those sequences in other ways. 
  • Lists are dynamic.
  • Lists are mutable.
  • Lists are ordered.
  • An index is used to traverse a list.

Lists help store multiple items and then iterate over them using a loop. Because lists are dynamic, you can easily add or remove items anytime.

What Is a Tuple in Python?

Tuples are also a sequence data type containing elements of different data types.

It comes in handy when storing a collection of items, especially if you want those items to be unchanging. 

A python tuple has the following features - 

  • Tuples are used to store heterogeneous and homogeneous data.
  • Tuples are immutable in nature.
  • Tuples are ordered
  • An index is used to traverse a tuple.
  • Tuples are similar to lists. It also preserves the data sequence.

As tuples are immutable, they are faster than the list because they are static.

List Syntax

A list is initiated with the [ ] symbol. 

Here’s an example of declaring a list in python.

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

print(num_list)

alphabets_list = [‘a’,‘b’,‘c’,‘d’,‘e’]

print(alphabets_list)

A list can contain data of different data types. You can initiate it as follows - 

mixed_list = [‘a’, 1,‘b’,2,‘c’,3,‘4’]

print(mixed_list)

You can create nested lists as well. A nested list is a list inside a list.

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

print(nested_list)

Tuple Syntax

A tuple is initiated with the () symbol. 

Here’s an example of declaring a tuple in python.

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

print(num_tuple)

alphabets_tuple = (‘a’,‘b’,‘c’,‘d’,‘e’)

print(alphabets_tuple)

A list can contain data of different data types. You can initiate it as follows - 

mixed_tuple = (‘a’, 1,‘b,’ 2,‘c,’ 3, ‘4’).

print(mixed_tuple)

You can create nested lists as well. A nested list is a list inside a list.

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

print(nested_tuple)

Data Science with Python

The Ultimate Ticket To Top Data Science Job RolesExplore Course
Data Science with Python

Syntax Differences

List and tuple act as containers for storing objects. But there is a difference in its use cases and syntax as well.

Lists are surrounded by square brackets [ ] while tuples are surrounded by round brackets ( ).

Creating a list and tuple in python.

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

tuple_numbers  = (1,2,3,4,5)

print(list_numbers)

print(tuple_numbers)

We can use the type function to check the data type of any object.

type(list_numbers)

type(tuple_numbers)

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

The contents of a tuple cannot change once they have been created in Python due to the immutability of tuples.

There is no way to keep changing tuples. Error message if you attempt to change one of the items:

names = ("Raj","John","Jabby","Raja")

names[2] = "Kelly"

Traceback (most recent call last):

File "<stdin>", line 4, in <module>

TypeError: 'tuple' object does not support item assignment

If you're familiar with lists and maps, you know that they can be modified. You can add or remove items or reassign them to different variables. But tuples? Well, you can't do any of that. 

The reason is simple: tuples are immutable, meaning you cannot change their contents after they are created. The length of tuples is also fixed. They remain the same length throughout the lifecycle of the program.

So why would we use immutable data structures like tuples anyway? Well, one reason is that they have a small overhead compared to mutable data structures like lists and maps. 

Difference Between List and Tuple (Table)

Following are the difference between list and tuple - 

Python Lists

Python Tuples

1

List are mutable

Tuples are immutable

2

Iterations are time-consuming

Iterations are comparatively Faster

3

Inserting and deleting items is easier with a list.

Accessing the elements is best accomplished with a tuple data type.

4

Lists consume more memory

Tuple consumes less than the list

5

Lists have several built-in methods.

A tuple does not have many built-in methods because of immutability

6

A unexpected change or error is more likely to occur in a list.

In a tuple, changes and errors don't usually occur because of immutability.

Free Course: Programming with Python

Learn the Basics of Programming with PythonEnroll Now
Free Course: Programming with Python

Mutable List vs. Immutable Tuples

We have heard already that tuples are immutable while lists are mutable. It simply means that you can change the existing values in a list. But you cannot change the same value if it is stored in the tuple.

Let’s take an example to understand the immutability of tuples

Create a new list list_num and initialize it with 5 values.

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

Let’s replace 3 with 5.

list_num[2] = 5

print(list_num)

[1,2,5,4,5]

Carrying out similar operation in tuple.

Create a new tuple tuple_num and initialize it with five values.

tuple_num=(1,2,3,4,5)

Let’s replace 3 with 5.

tup_num[2] = 7

It will the following error - 

[1,2,7,4,5]

Traceback (most recent call last): 

 File "python", line 3, in <module> 

TypeError: 'tuple' object does not support item assignment.

The error makes it clear that item assignment is not supported in the tuple. Hence it is immutable.

Available Operations

As the list is mutable, it has many inbuilt operations that you can use for achieving varied results. Let’s take a look at such list operations.

append()

It is used to add elements to the list. The elements get added at the end of the list. You can add only one element at once. Using a loop will let you add multiple elements at once.

numList = [1,2,3]

numList.append(4)

numList.append(5)

numList.append(6)

Using a loop for insertion

for i in range(7, 9):

    numList.append(i)

print(numList)

extend()

Extend operation is used to add elements at the end of the list like append operation. But extend() allows you to add multiple elements at once.

numList = [1,2,3]

numList.extend([4, 5, 6]) 

print(numList)

insert()

It allows you to add a new element in the list in a given position. Unlike append, it does not add elements at the end. It takes two arguments, the first argument is the position, and the second argument is the element. You can insert one element at once. Hence for inserting multiple elements, you can use a loop.

numList = [1,2,3]

numList.insert(3, 4)

numList.insert(4, 5)

numList.insert(5, 6)

print(numList)

remove()

It is used to remove an element from the list. If there are multiple elements, only the first occurrence of the element is removed.

stringList = ['List', 'makes learning fun!', 'for us!']

stringList.remove('makes learning fun!')

print(stringList)

pop()

It is used to remove elements from any position in the list. Pop() takes one argument, the position of the element.

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

numList.pop(4)

print(numList)

slice.

It is used to print a subset of the list. You have to specify starting position and ending position for the slicing operation. 

numList = [1,2,3,4,5,6,7,8,9]

print(numList[:9])  # prints from beginning to end index

print(numList[2:])  # prints from start index to end of list

print(numList[2:9]) # prints from start index to end index

print(numList[:])   # prints from beginning to end of list

Free Course: Python for Beginners

Master the fundamentals of PythonEnroll Now
Free Course: Python for Beginners

reverse()

Reverse operation reverses the original list. If you want to reverse without affecting the original list, you should use the slice function with a negative index.

numList = [1,2,3,4,5,6,7,8,9]

print(numList[::-1])  # does not modify the original list

numList.reverse()     # modifies the original list

print(numList)

len()

It returns the length of the list

numList = [1,2,3,4,5,6,7,8,9]

print(len(numList))

min()

It returns the minimum value in the list. You can use min operation successfully only if the list is homogenous. 

print(min([1, 2, 3]))

max()

It returns the maximum value in the list. You can use min operation successfully only if the list is homogenous. 

print(max([1, 2, 3]))

count()

Count operation returns the count of specified element in the list. It takes the element as an argument.

numList = [1,2,2,4,4,6,8,8,9]

print(numList.count(3))

concate()

It is used to merge two lists into a new list. + sign is used to combine two lists.

numList = [4,5]

stringList = ['Python', 'is fun!']

print(numList+stringList )

multiply()

Python also allows multiplying the list n times. The resultant list is the original list iterated n times.

numList = [1,2,3,4,5,6,7,8,9]

print(numList*2)

index()

It is used to find an element based on the index position. You need to pass two arguments to it, the first is the starting position, and the second is the ending position. When supplied, the element is searched only in the sub-list bound by the begin and end indices. When not supplied, the element is searched in the whole list.

print(stringList.index('HelloWorld'))            # searches in the whole list

print(stringList.index('HelloWorld', 0, 2))     # searches from 0th to 2nd position

sort()

It is used to sort the list in ascending order. You can perform this operation only on a homogeneous list. Using sort() on a heterogeneous list will throw an error.

numList = [4, 2, 6, 5, 0, 1]

numList.sort()

print(numList)

clear()

It clears all the elements from the list and empties it.

numList = [1,2,3,4,5,6,7,8,9]

numList.clear()

print(numList)

Immutability reduces the number of inbuilt functions a tuple has. Let’s take a look at such tuple operations.

min()

It returns the minimum value in the tuple. You can use the min operation successfully only if the tuple is homogenous. 

print(min((1, 2, 3)))

Free Course: Python Libraries for Data Science

Learn the Basics of Python LibrariesEnroll Now
Free Course: Python Libraries for Data Science

max()

It returns the maximum value in the tuple. You can use min operation successfully only if the tuple is homogenous. 

print(max((1, 2, 3)))

slice.

It is used to print a subset of the tuple. You have to specify starting position and ending position for the slicing operation. 

myTuple = [1,2,3,4,5,6,7,8,9]

print(myTuple[:9])  # prints from beginning to end index

print(myTuple[2:])  # prints from start index to end of tuple

print(myTuple[2:9]) # prints from start index to end index

print(myTuple[:])   # prints from beginning to end of tuple

len()

It returns the length of the tuple

myTuple = [1,2,3,4,5,6,7,8,9]

print(len(myTuple))

del()

Tuples are immutable, but we can remove the tuple elements using del operation.

Tuple1 = (1, 3, 4, 'test', 'red')

del (Tuple1[1])

Membership In Tuple

If you want to check whether an element belongs to the tuple or not, you can use a keyword to check its membership.

Tuple1 = (1, 3, 4, 'test', 'red')

print (1 in Tuple1)

print (5 in Tuple1)

Size Comparison

There is a difference in lengths between the two data structures. The length of a tuple is fixed, whereas the length of a list is variable. Therefore, lists can have a different sizes, but tuples cannot.

Tuples are allocated large blocks of memory with lower overhead than lists because they are immutable; whereas for lists, small memory blocks are allocated. Thus, tuples tend to be faster than lists when there are a large number of elements.

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

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

print('a=',a.__sizeof__())

print('b=',b.__sizeof__())

a=104

b=120

Different Use Cases

Python's lists are best suited to store data in the following situations: 

  1. Several types of data can be stored in lists, and their index can be used to access them.
  2. Lists are good for mathematical operations on a group of elements because Python allows you to perform these operations directly on the list. 
  3. If you don't know how many elements will be stored in your list ahead of time, it's easy to increase or decrease its size as needed.

Python's tuples are best suited to store data in the following situations: 

  1. It’s best to use a tuple when you know the exact information that will go into the object's fields. 
  2. For example, if you want to store credentials for your website, it’s okay to use a tuple. 
  3. The tuples are immutable (unchangeable), so they can only be used as keys for dictionaries. But if you want to use a list as a key, make it into a tuple first.

Examples

Tuples as Dictionary

As tuples are hashable, you can use them as keys for dictionaries.

tuplekey = {}

tuplekey[('blue', 'sky')] = 'Good'

tuplekey[('red','blood')] = 'Bad'

print(tuplekey)

Tuple Packing and Unpacking

Packing and unpacking improves the code readability. 

Packing means assigning multiple values to the tuple.

Unpacking means assigning values to individual variables.

Tuple Packing

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

print(person)

Tuple Unpacking

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

(name, height, profession) = person

print(name)

print(height)

print(profession)

When to Use Tuples Over Lists?

Tuples are immutable. Hence they are primarily used to store data that doesn't change frequently. Any operation can store data in a tuple when you don't want it to change.

Tuples are great to use if you want the data in your collection to be read-only, never to change, and always remain the same and constant.

Because of this ability and the guarantee that data is never changed, you can use tuples in dictionaries and sets, which require the elements inside them to be of an immutable type.

It is beneficial when you need to store values that don't change over time, like a person's birthdate or height.

Learn data operations in Python, strings, conditional statements, error handling, and the commonly used Python web framework Django with the Python Training course.

Conclusion

Now that you have an in-depth understanding of List and Tuples in Python, take a deep dive into more Python concepts with Simplilearn’s Python Certification Course. This course covers the basics of Python, data operations, conditional statements, shell scripting, and Django. Get certified in Python and boost your career today!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.