In Python, both lists and tuples are used to store multiple items or collections of values. However, there are few differences between them:
Now, let's see a scenario where we would use a tuple instead of a list and why.
Assume that we want to create a collection of items containing the name, age, and gender of a person. Since these details are not going to change frequently, we can use a tuple to store them. A tuple provides better optimization, as it takes less memory and executes faster.
Here's an example code snippet:
person_details = ('John', 34, 'Male')print(person_details)
Output:
('John', 34, 'Male')
In this example scenario, we have used a tuple to store the name, age, and gender of a person. We can use it to access the details of a person as shown below:
# Access tuple elementsname, age, gender = person_detailsprint("Name:", name)print("Age:", age)print("Gender:", gender)
Output:
Name:
JohnAge:
34Gender:
Male
Citations: