Why are there separate tuple and list data types in Python?


Separate tuple and list data types are provided because both have different roles. Tuples are immutable, whereas lists are mutable. That means, Lists can be modified, whereas Tuple cannot.

Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

Let’s see how Lists and Tuples are created.

Create a basic Tuple

Example

Let us first create a basic Tuple with integer elements and then move towards Tuples within a Tuple

# Creating a Tuple mytuple = (20, 40, 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple))

Output

Tuple =  (20, 40, 60, 80, 100)
Tuple Length=  5

Create a Python List

Example

We will create a list with 10 integer elements and display it. The elements are enclosed by square brackets. With that, we have also displayed the length of the list and how we can access specific elements using the square brackets −

# Create a list with integer elements mylist = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180]; # Display the list print("List = ",mylist) # Display the length of the list print("Length of the List = ",len(mylist)) # Fetch 1st element print("1st element = ",mylist[0]) # Fetch last element print("Last element = ",mylist[-1])

Output

List =  [25, 40, 55, 60, 75, 90, 105, 130, 155, 180]
Length of the List =  10
1st element =  25
Last element =  180

Can we update Tuple Values?

Example

As said above, Tuples are immutable and cannot be updated. But, we can convert the Tuple to List and then update it.

Let’s see an example −

myTuple = ("John", "Tom", "Chris") print("Initial Tuple = ",myTuple) # Convert the tuple to list myList = list(myTuple) # Changing the 1st index value from Tom to Tim myList[1] = "Tim" print("Updated List = ",myList) # Convert the list back to tuple myTuple = tuple(myList) print("Tuple (after update) = ",myTuple)

Output

Initial Tuple =  ('John', 'Tom', 'Chris')
Updated List =  ['John', 'Tim', 'Chris']
Tuple (after update) =  ('John', 'Tim', 'Chris')

Updated on: 16-Sep-2022

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements