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.

Key Difference Between List and Tuple

The main difference between tuples and lists is that tuples can't be changed after they're created, but lists can be modified. Tuples use less memory than lists. They are also a bit faster, especially when you're just looking up values. So, if you have data that you don't want to change, it's better to use tuples instead of lists.

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.

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)

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.

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)

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 primary difference between tuples and lists is that tuples are immutable as opposed to lists which are mutable. Therefore, it is possible to change a list but not a tuple.

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

List are mutable

Tuples are immutable

Iterations are time-consuming

Iterations are comparatively Faster

Inserting and deleting items is easier with a list.

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

Lists consume more memory

Tuple consumes less than the list

Lists have several built-in methods.

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

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.

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

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)))

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.

Choose The Right Software Development Program

This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.

Program Name Full Stack Java Developer Career Bootcamp Automation Testing Masters Program Post Graduate Program in Full Stack Web Development
Geo IN All Non-US
University Simplilearn Simplilearn Caltech
Course Duration 11 Months 11 Months 9 Months
Coding Experience Required Basic Knowledge Basic Knowledge Basic Knowledge
Skills You Will Learn 15+ Skills Including Core Java, SQL, AWS, ReactJS, etc. Java, AWS, API Testing, TDD, etc. Java, DevOps, AWS, HTML5, CSS3, etc.
Additional Benefits Interview Preparation
Exclusive Job Portal
200+ Hiring Partners
Structured Guidance
Learn From Experts
Hands-on Training
Caltech CTME Circle Membership
Learn 30+ Tools and Skills
25 CEUs from Caltech CTME
Cost $$ $$ $$$
Explore Program Explore Program Explore Program

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!

If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn's Post Graduate Program in Full Stack Web Development. This program can help you acquire the right development skills and make you job-ready in no time.

If you have any questions, feel free to post them in the comments section below. Our team will get back to you at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 15 Apr, 2024

6 Months$ 8,000
Full Stack Java Developer

Cohort Starts: 2 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 3 Apr, 2024

11 Months$ 1,499
Full Stack Developer - MERN Stack

Cohort Starts: 3 Apr, 2024

6 Months$ 1,449

Get Free Certifications with free video courses

  • Getting Started with Full Stack Java Development

    Software Development

    Getting Started with Full Stack Java Development

    12 hours4.538.5K learners
  • Full-Stack Development 101: What is Full-Stack Development ?

    Software Development

    Full-Stack Development 101: What is Full-Stack Development ?

    1 hours4.47.5K learners
prevNext

Learn from Industry Experts with free Masterclasses

  • Fuel Your 2024 FSD Career Success with Simplilearn's Masters program

    Software Development

    Fuel Your 2024 FSD Career Success with Simplilearn's Masters program

    21st Feb, Wednesday9:00 PM IST
  • Break into a Rewarding Full Stack Developer Career with Mern Stack

    Software Development

    Break into a Rewarding Full Stack Developer Career with Mern Stack

    2nd Apr, Tuesday9:00 PM IST
  • Java vs JavaScript: The Right Learning Path for You in 2024

    Software Development

    Java vs JavaScript: The Right Learning Path for You in 2024

    19th Mar, Tuesday9:00 PM IST
prevNext