Difference between List and Tuple in Python

Lists and Tuple store one or more objects or values in a specific order.

The objects stored in a list or tuple can be of any type including the nothing type defined by the None Keyword.

Syntax Differences

Syntax of list and tuple is slightly different.

List are surrounded by square brackets [] and Tuples are surrounded by parenthesis ().

Example: Creating List vs. Creating Tuple

Mutable List vs Immutable Tuples

List has mutable nature i.e., list can be changed or modified after its creation according to needs whereas tuple has immutable nature i.e., tuple can’t be changed or modified after its creation.

Example: Try to Modify an item List vs. Tuple

Available operations

Lists has more built-in function than that of tuple. We can use dir([object]) inbuilt function to get all the associated functions for list and tuple.

Size Comparison

Tuple operation has smaller size than that of list, which makes it a bit faster but not that much to mention about until you have a huge number of elements.

Example: Calculate size of List vs. Tuple

Different Use Cases

At first sight, it might seem that lists can always replace tuples. But tuples are extremely useful data structures

  1. Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed.
  2. tuples are commonly used as the equivalent of a dictionary without keys to store data.

Different Use Cases

3. Reading data is simpler when tuples are stored inside a list. For example,

Is easier to read than

4. Tuple can also be used as key in dictionary due to their hashable and immutable nature whereas lists are not used as key in a dictionary because list can’t handle __hash__() and have mutable nature.

Key points to remember:

  1. The literal syntax of tuple is shown by parenthesis() whereas the literal syntax of lists is shown by square brackets[].
  2. List has variable length, tuple has fixed length.
  3. List has mutable nature, tuple has immutable nature.
  4. List has more functionality than the tuple.

Popular Posts

Author

  • Naveen Pandey Data Scientist Machine Learning Engineer

    Naveen Pandey has more than 2 years of experience in data science and machine learning. He is an experienced Machine Learning Engineer with a strong background in data analysis, natural language processing, and machine learning. Holding a Bachelor of Science in Information Technology from Sikkim Manipal University, he excels in leveraging cutting-edge technologies such as Large Language Models (LLMs), TensorFlow, PyTorch, and Hugging Face to develop innovative solutions.

    View all posts
Spread the knowledge
 
  

One thought on “Difference between List and Tuple in Python

Leave a Reply

Your email address will not be published. Required fields are marked *