What is the difference between a tuple and a list?
tuples vs lists
python - List vs tuple, when to use each? - Stack Overflow
Tuples vs Lists, when do you decide which one you use?
What is an example of a tuple?
What is the biggest difference between a tuple and a list?
Why is a tuple faster than a list?
Ive gotten through chapter 4 of Python crash course and dont know what the big difference between the two are.
So below i was wondering what the difference is in using a tuple vs a list in a dictionary below is the code. IK that lists are easier to modify and that tuples are immutable but like how does that actually come into effect in code. If someone could give an example that would be great. So ig you would use a list if you wanted to append or change the data?
course = { "language": ["French", "German"], "duration": "3 months" } print(course)
vs
course = { "language": ("French", "German"), "duration": "3 months" } print(course)
Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.
- You can't add elements to a tuple. Tuples have no append or extend method.
- You can't remove elements from a tuple. Tuples have no remove or pop method.
- You can find elements in a tuple, since this doesn’t change the tuple.
- You can also use the
inoperator to check if an element exists in the tuple.
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 mutable.
Source: Dive into Python 3
There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.