In many places, (1,2,3)
(a tuple) and [1,2,3]
(a list) can be used interchangeably.
When should I use one or the other, and why?
(1,2,3) and [1,2,3] can be used interchangeably in rare conditions.
So (1,2,3) is a tuple and is immutable. Any changes you wish to make need to overwrite the object.
[1,2,3] is a list and elements can be appended and removed.
List has more features than a tuple.
(1,2,3)
is a tuple while [1,2,3]
is a list. A tuple is an immutable object while a list is mutable.
Tuples are a quick\flexible way to create composite data-types. Lists are containers for, well, lists of objects.
For example, you would use a List to store a list of student details in a class.
Each student detail in that list may be a 3-tuple containing their roll number, name and test score.
`[(1,'Mark',86),(2,'John',34)...]`
Also, because tuples are immutable they can be used as keys in dictionaries.
As others have mentioned, Lists and tuples are both containers which can be used to store python objects. Lists are extensible and their contents can change by assignment, on the other hand tuples are immutable.
Also, lists cannot be used as keys in a dictionary whereas tuples can.
a = (1,2,3) is a tuple which is immutable meaning you can't add anything into a b = [1,2,3] is a list in python which is immutable meaning you can make changes into 'b' either delete or add numbers into it.