Home > Article > Backend Development > Why are there separate tuple and list data types in Python?
Provide separate tuple and list data types because the two have different roles. Tuples are immutable, while lists are mutable. This means that lists can be modified, but tuples cannot.
Tuples are sequences, just like lists. The difference between tuples and lists is that unlike lists, tuples cannot be changed and tuples use brackets while lists use square brackets.
Let's see how to create lists and tuples.
Let's first create a basic tuple containing integer elements and then move on to tuples within tuples
# Creating a Tuple mytuple = (20, 40, 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple))
Tuple = (20, 40, 60, 80, 100) Tuple Length= 5
We will create a list of 10 integer elements and display it. Elements are enclosed in square brackets. This way we also show the length of the list and how to access specific elements using 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])
List = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180] Length of the List = 10 1st element = 25 Last element = 180
As mentioned above, tuples are immutable and cannot be updated. However, we can convert the Tuple to a 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)
Initial Tuple = ('John', 'Tom', 'Chris') Updated List = ['John', 'Tim', 'Chris'] Tuple (after update) = ('John', 'Tim', 'Chris')
The above is the detailed content of Why are there separate tuple and list data types in Python?. For more information, please follow other related articles on the PHP Chinese website!