Home  >  Article  >  Backend Development  >  Are python collections ordered?

Are python collections ordered?

anonymity
anonymityOriginal
2019-06-14 15:55:098445browse

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

Are python collections ordered?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn