
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Creating a Basic Tuple
We will begin the code by creating a basic tuple with integer elements. Next, specify the topics as advanced concepts like tuples nested within tuples. The provided code initializes a tuple, displays its elements, and calculates its length using Python's len() function.
# Creating a Tuple mytuple = (20, 40, 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple))
The result is obtained as follows -
Tuple = (20, 40, 60, 80, 100) Tuple Length= 5
Creating a List Datatype
A list containing 10 integer elements will be created and displayed, with the elements enclosed in square brackets. Additionally, the length of the list will be displayed, along with demonstrating 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])
The output is produced as follows -
List = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180] Length of the List = 10 1st element = 25 Last element = 180
Updating Tuple Values
Tuples are immutable, their elements cannot be directly modified. However,by converting a tuple into a list, updates can be made. The provided code demonstrates this by converting a tuple to a list, modifying an element, and then converting it back to a tuple while displaying the changes.
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)
We will get the output as follows -
Initial Tuple = ('John', 'Tom', 'Chris') Updated List = ['John', 'Tim', 'Chris'] Tuple (after update) = ('John', 'Tim', 'Chris')