In this post, we will understand the differences between list and tuple in Python.
List and tuple are two different kinds of data structures used in Python. They are both used in different instances to store data of different types.
It is often referred to as a sequence. It is considered to be one of the most frequently used data type, as well as lauded for its versatility. A list can be created by placing all elements inside square brackets ([ ]) and separating the elements with commas. There can be any number of elements inside the list and they can be of different types as well (such as integer, float, string, and so on). The most important characteristic of list is that it is a mutable structure, i.e changes can be made by references the list.
Let us see how a list with heterogeneous data types can be created −
my_list = [1.8, 'string', 34, 'a'] print(my_list)
[1.8, 'string', 34, 'a']
There are many ways in which data within a list can be accessed.
Let us see how indexing can be used to access elements −
my_list = [1.8, ‘string’, 34, ‘a’] print(“The second element is”) print(my_list)
The second element is string
We can also access elements from one range to another. This is known as list slicing. Let us see how that can be done −
my_list = [1.8, 'string', 34, 'a'] print("The elements within a certain range are") print(my_list[1:4])
The elements within a certain range are ['string', 34, ‘a’]
We can also change the values of a list by performing indexing and assigning a new value to that index. Let us see how that can be done −
my_list = [1.8, 'string', 34, 'a'] print(“List before changes”) print(my_list) my_list = ‘my_string’ print("List after changes") print(my_list)
List before changes [1.8, 'string', 34, 'a'] List after changes [1.8, 'my_string', 34, 'a']
Now let us understand the working of a tuple structure. It is created using parenthesis, i.e. (). The important characteristic of tuple is that it is immutable, i.e. the elements one assigned inside a tuple can't be changed by accessing the tuple. There can be any number of elements inside the tuple and they can be of different types as well (such as integer, float, string, and so on).
Note: A tuple can be created without the use of parenthesis, but it is considered good practice to use parenthesis.
Let us see how a tuple with a single element can be created −
my_tuple = (“hey”,) print(“Creating a tuple with one element”) print(my_tuple)
Note: Accessing the elements of the tuple, negative indexing, and list slicing are same as that of list.
If the tuple contains a list inside it, that list can be changed, but elements that are only inside the tuple, but not inside the list, can't be changed.