Are python collections ordered?

anonymity
Release: 2019-06-14 15:55:09
Original
8523 people have browsed it

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']
Copy after login

List can store different types of data:

L = ['A',123,True]
Copy after login

If you want to define an empty tuple, you can write it as ( )

t = ()
print(t)
>>>()
Copy after login

If you define a tuple of an element, write it as:

t = (1)
print(t)
>>>1
Copy after login

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,)
Copy after login

The above is the detailed content of Are python collections ordered?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template