>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2
Are they both valid? Is one preferred for some reason?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
while tuples are not:
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
Note that, as many people have pointed out, you can add tuples together. For example:
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
Whereas, if you were to construct this same example with a list,
ywould also be updated: