Does python have immutable lists?
Suppose I wish to have the functionality of an ordered collection of elements, but which I want to guarantee will not change, how can this be implemented? Lists are ordered but they can be mutated.
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.
Yes. It’s called a
tuple.So, instead of
[1,2]which is alistand which can be mutated,(1,2)is atupleand cannot.Further Information:
A one-element
tuplecannot be instantiated by writing(1), instead, you need to write(1,). This is because the interpreter has various other uses for parentheses.You can also do away with parentheses altogether:
1,2is the same as(1,2)Note that a tuple is not exactly an immutable list. Click here to read more about the differences between lists and tuples