Difference Between List and Tuple in Python

PythonServer Side ProgrammingProgramming

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.

List

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 −

Example

Live Demo

my_list = [1.8, 'string', 34, 'a']
print(my_list)

Output

[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 −

Example

my_list = [1.8, ‘string’, 34, ‘a’]
print(“The second element is”)
print(my_list[1])

Output

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 −

Example

Live Demo

my_list = [1.8, 'string', 34, 'a']
print("The elements within a certain range are")
print(my_list[1:4])

Output

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 −

Example

my_list = [1.8, 'string', 34, 'a']
print(“List before changes”)
print(my_list)
my_list[1] = ‘my_string’
print("List after changes")
print(my_list)

Output

List before changes
[1.8, 'string', 34, 'a']
List after changes
[1.8, 'my_string', 34, 'a']

Tuple

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 −

Example

my_tuple = (“hey”,)
print(“Creating a tuple with one element”)
print(my_tuple)

Output

("hello")

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.

raja
Published on 02-Mar-2021 04:50:33
Advertisements