Interview Question for python developer at TCS
Home
Refer
Jobs
Alumni
Resume
Notifications

What is the difference between a list and a tuple in Python? Can you provide an example scenario where you would use a tuple instead of a list, and why?

🚀 Best Answers Get Featured in our LinkedIn Community based on Your Consent, To Increase Your Chances of Getting Interviewed. 🚀

Difference between List and Tuple in Python

In Python, both lists and tuples are used to store multiple items or collections of values. However, there are few differences between them:

  • Lists are mutable, which means the values or items can be changed after they are created. Tuples are immutable, meaning that once created, the values cannot be altered.
  • List uses square brackets([]), whereas tuples use the parenthesis(()).
  • Lists have a larger memory footprint compared to tuples because they can grow or shrink dynamically. Tuples have a smaller memory footprint, and hence, are considered more optimized.

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:

© 2024 Referral Solutions, Inc. Incorporated. All rights reserved.