+ 1
What is the difference between tuple and list?
5 Respostas
+ 6
The tuple after creation cannot be changed or sorted.
+ 2
Lists:
- [ ] are used to create lists e.g [a,b,2]
- mutable(changeable) values or content within the list can be changed after its creation
Tuples:
- () are used to create tuple e.g (a,b,1)
- immutable (unchangeable): values or content within the tuple cannot be changed after its creation (cannot add, delete item to and from it)
Similarities:
- Both are ordered
- You can access tuple/list items by referring to the index number, inside square brackets e.g.
my_list = [1,2,3,4,5]
my_tuple = (1,2,3,4,5)
print(my_list[2])
print("\n")
print(my_tuple[4])
Output:
3
5
I hope this clears your query :)
+ 1
Tuple is a container that doesn't allow to add, delete or shift items in them.
List allow you all kinds of manipulations of content and order.
+ 1
Great answer Muhammad Shehzad - but why would you need tuples instead of lists?
+ 1
Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.
It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.
Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.
Source: stackoverflow
nice question Anhjje 🐿 :)