Difference between List and Tuple in Python
- Naveen
- 1
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
- Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed.
- 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:
- The literal syntax of tuple is shown by parenthesis() whereas the literal syntax of lists is shown by square brackets[].
- List has variable length, tuple has fixed length.
- List has mutable nature, tuple has immutable nature.
- List has more functionality than the tuple.
You are my breathing in, I have few web logs and rarely run out from to brand.