Tuple vs List
What You'll Learn: In this tutorial, you'll discover the differences and common properties between tuples and lists in Python. This will help you understand when to use each type.
Key Differences and Properties
| Property | Tuple | List |
|---|---|---|
| Definition | Immutable collection of ordered items. | Mutable collection of ordered items. |
| Mutation | Immutable. Items cannot be changed. | Mutable. Items can be changed. |
| Append Item | Cannot be done directly on the tuple. Workaround needed. | Can append an item to the list. |
| Edit/Update Item | Cannot be done directly on the tuple. | Use index on the list and assign a new value. |
| Delete Item | Tuple can be deleted entirely but not a single item. | Can delete an item from the list using del keyword. |
| Access Items | Items can be accessed using index. | Items can be accessed using index. |
| Iterate over Items | You may use for loop or while loop to iterate over items. | You may use for loop or while loop to iterate over items. |
Summary:
From the table, it is clear that the major difference between a tuple and a list in Python is that a tuple is immutable (unchangeable) while a list is mutable (changeable). Mutable means the collection can be changed, like mutation in genetics.
Examples and Exercises:
- Mutable vs Immutable:
- Create a list and a tuple with the same items. Try to change one item in the list and see how it works. Try to change an item in the tuple and observe what happens.
- Appending to a List:
- Create a list and add a new item to it using the
append()method. Try the same with a tuple and see why it doesn't work.
- Create a list and add a new item to it using the
- Deleting Items:
- Create a list and delete an item using the
delkeyword. Try to delete an item from a tuple and see the difference.
- Create a list and delete an item using the
Summary:
In this Python tutorial, we learned the key differences and common properties between tuples and lists. Tuples are immutable, making them suitable for fixed collections, while lists are mutable and can be changed. Understanding these properties will help you choose the right data structure for your needs. Keep experimenting and have fun with tuples and lists in Python!