What is the difference between tuple and list? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

What is the difference between tuple and list?

31st Jul 2019, 1:52 PM
Stuti Yadav
Stuti Yadav - avatar
5 Réponses
+ 6
The tuple after creation cannot be changed or sorted.
31st Jul 2019, 2:00 PM
Mikhail Gorchanyuk
Mikhail Gorchanyuk - avatar
+ 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 :)
31st Jul 2019, 2:05 PM
Muhammad Shehzad
Muhammad Shehzad - avatar
+ 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.
31st Jul 2019, 1:59 PM
HonFu
HonFu - avatar
+ 1
Great answer Muhammad Shehzad - but why would you need tuples instead of lists?
31st Jul 2019, 2:10 PM
HNNX 🐿
HNNX 🐿 - avatar
+ 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 🐿 :)
31st Jul 2019, 2:14 PM
Muhammad Shehzad
Muhammad Shehzad - avatar