Home > Article > Backend Development > Are python collections ordered?
A collection refers to a data structure containing a set of elements, including:
1. Ordered collection : list, tuple, str and unicode;
2. Unordered set : set
3. Unordered set with key-value pair: dict Traversal
Take an example to learn an ordered set in Python:
Python’s built-in ordered sets include list and tuple. The former is mutable and the latter is immutable.
List elements can be replaced, such as:
classmates = ['alice','bob','jack'] classmates[1] = 'tracy' >>>classmates ['alice','tracy','jack']
List can store different types of data:
L = ['A',123,True]
If you want to define an empty tuple, you can write it as ( )
t = () print(t) >>>()
If you define a tuple of an element, write it as:
t = (1) print(t) >>>1
What you define is not a tuple, but the number 1! This is because brackets () can represent both tuples and parentheses in mathematical formulas, which creates ambiguity. Therefore, Python stipulates that in this case, the calculation is performed according to parentheses, and the calculation result is naturally 1.
Therefore, a comma must be added when defining a tuple with only one element to eliminate ambiguity:
t = (1,) print(t) >>>(1,)
The above is the detailed content of Are python collections ordered?. For more information, please follow other related articles on the PHP Chinese website!