July 27, 2018
Difference between list and tuple in Python
Introduction
So you are curious to know the key difference between a list and tuple in Python ? You can find the answer in many places on the web, however in this code snippet we will summarize it so that it is easy to remember. Take a look at the following table…
List vs Tuple in Python
Here are the main differences…
Python List | Python Tuple |
---|---|
Collection data type | Collection data type |
Mutable (i.e. can be modified) | Immutable (i.e. cannot be modified) |
Use square brackets [] to define | Use parenthesis () to define |
Can hold data of different types | Can hold data of different types |
Elements are ordered | Elements are ordered |
Mainly used to collect similar Items (can be tuples) | Mainly used to group data as one item |
Similar to arrays in other languages | Similar to records or struct in other languages |
Code
Let us now demonstrate the concepts mentioned in the table above…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Define tuples (ex. addresses) fremont = (3000, "Macmillan Way", "Fremont", "CA", 94555) sanjose = (4000, "Tasman Drive", "San Jose", "CA", 95123) # Define a list of locations. We can modify the list # by appending more addresses locations = [] locations.append(fremont) locations.append(sanjose) # This will print: # <type 'tuple'> in Python 2 or # <class 'tuple'> in Python 3 print(type(fremont)) # This will print: # <type 'list'> in Python 2 or # <class 'list'> in Python 3 print(type(locations)) # Try to modify a tuple. This is going to trigger # the exception. It should print: # 'tuple' object does not support item assignment try: fremont[0] = 5000 except Exception as e: print(e) # Once a tuple is declared, we can reassign it # this will print: # (4000, 'Macmillan Way', 'Fremont', 'CA', 94555) fremont = (4000, "Macmillan Way", "Fremont", "CA", 94555) print(fremont) |
If we run the code snippet code above, we should get the following output:
1 2 3 4 |
# <type 'tuple'> # <type 'list'> # 'tuple' object does not support item assignment # (4000, 'Macmillan Way', 'Fremont', 'CA', 94555) |
That is all for today. Thanks for visiting.