Table of Contents
A versatile and powerful language, Python provides various element types such as list and tuple. Each of these elements has its own unique properties and functions. Let’s dive deeper into understanding each of these elements.
Lists and tuples are the two basic classes of data structures in Python. Although they may seem similar, they have unique characteristics that set them apart.
Distinguishing Between List, Tuple in Python
Let’s delve into the differences between List, Tuple, Set, and Dictionary in Python:
Parameters | List | Tuple |
Basics | A list is similar to an array in other languages (like ArrayList in Java or vector in C++). | Tuples are collections of Python objects separated by commas. |
Homogeneity | A list is a non-homogeneous data structure that stores elements in columns and rows. | A tuple is a non-homogeneous data structure that stores elements in columns and rows. |
Representation | A List is represented by [ ] | A Tuple is represented by ( ) |
Duplicate elements | It permits duplicate elements. | It permits duplicate elements. |
Nested Among All | It can be nested in a List. | It can be nested in a Tuple. |
Example | [1, 2, 3, 4, 5] | (10, 20, 30, 40, 50) |
Function for Creation | A list can be created using the list() function. | A tuple can be created using the tuple() function. |
Mutation | It is mutable, allowing modifications. | It is immutable, not allowing modifications. |
Order | It maintains order. | It maintains order. |
Empty Elements | An empty list can be created using:
l=[] |
An empty tuple can be created using:
t=() |
What is a List?
In other programming languages, list objects are declared similarly to arrays. Lists need not always be homogeneous, so they can simultaneously store items of different data types. Lists thus become the most useful tool. A list is a type of Python container data structure used to store many pieces of data at once. Lists are useful when we need to iterate over some elements and keep items.
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.
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?
1: Which of the following data types is immutable in Python?
A tuple is another data structure for storing a collection of items of many data types, but unlike mutable lists, tuples are immutable. In other words, a tuple is a collection of items separated by commas. Because of its static structure, a tuple is more efficient than a list.
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.
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)
“Get hands-on with our python course – sign up for a free demo!”
Difference Between List and Tuple in Python (An In-Depth Explanation)
The primary difference between tuples and lists is that tuples are immutable, unlike lists, which are mutable. Therefore, it is possible to change a list, but not a tuple.
The contents of a tuple cannot change once it has 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 edited. 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, which means that once you create them, you can’t change their contents. The length of the tuples is also fixed. They remain the same length throughout the program’s life cycle.
So why would we use immutable data structures like tuples anyway? One reason is that they have little overhead compared to mutable data structures like lists and maps.
Mutable List vs. Immutable Tuples
We have already heard that tuples are immutable while lists are mutable. It simply means that you can change the existing values in the list. But you cannot change the same value if it is stored in a 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
Because a list is mutable, it has many built-in operations that you can use to achieve different results. Let’s look at such list operations.
append()
Used to add elements to the list. Elements are added to the end of the list. You can only add one element at a time. Using a loop allows you to 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()
The extension operation is used to add elements to the end of a list, like the join operation. But extend() allows you to add multiple elements at once.
numList = [1,2,3]
numList.extend([4, 5, 6])
print(numList)
insert()
Allows you to add a new element to the list at a given position. Unlike append, it does not add elements to 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 a time. So you can use a loop to insert multiple elements.
numList = [1,2,3]
numList.insert(3, 4)
numList.insert(4, 5)
numList.insert(5, 6)
print(numList)
remove()
Used to remove an element from a 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()
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.
Used to print a subset of a list. You must specify a start and end 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)))
Key Differences Between List and Tuple in Python
- Lists are mutable, while tuples are immutable.
- i.e., the elements of the list can be changed, after the creation, while the elements of the tuples can’t be modified.
- The size of the tuples is fixed, while the list can have a variable size.
- i.e., elements can be added or removed from the list but can’t be done in the tuple.
- Since tuples are immutable, they are generally faster than the list.
- Lists are used for data that needs to be changed frequently, while tuples are used for data that doesn’t need to be changed frequently.
Key Similarities Between List and Tuple in Python
- They both hold collections of items and are heterogeneous data types, meaning they can contain multiple data types simultaneously.
- They’re both ordered, which implies the items or objects are maintained in the same order as they were placed until changed manually.
- Because they’re both sequential data structures, we can iterate through the objects they hold; hence, they are iterables.
- An integer index, enclosed in square brackets [index], can be used to access objects of both data types.