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

Are python collections mutable?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-19 18:07:247081browse

A set is an unordered, mutable sequence. The elements in the collection must be hashable, that is, immutable data types.

Empty collection

a=set()

Note that a={} creates an empty dictionary.

Are python collections mutable?

set - a mutable set. Elements in the collection can be added or deleted dynamically.

frozenset - Immutable collection. The elements in the collection are immutable.

Note: The return value of union, intersection, difference, etc. has the same type as the leftmost operand. For example: s & t take the intersection. If the s collection is a set type collection and the t collection is a frozenset type collection, the returned result will be a set type collection.

Related recommendations: "Python Video Tutorial"

You can also use set() to convert it into a set

b=[1,2,3,4]
a=set(b)
a
{1,2,3,4}

You can also use {} to create one Set

a={1,2,3,4,1}
a
{1,2,3,4}

is the same as a dictionary, because the set is unordered, so when there are duplicate elements, only one of them is retained.

An immutable set is an unordered immutable set

Use frozenset(seq) to create

a=frozenset([1,2,3,(1,2,4)])
a
frozenset({1,2,3,(1,2,4)})

Elements can only be hashable The

frozenset([1,2,3,[1,2,4]])
error

is mainly used as a dictionary key. . The difference from tuple is that it is unordered, the elements are not repeatable, and the elements can only be of immutable type.

Description: You can convert other combined data types into immutable collection types (or convert mutable collection type set into immutable collection type frozenset), and return an immutable collection type with no duplicate elements and arbitrary ordering. variable set.

frozenset() function

Syntax: frozenset() -> empty frozenset object Returns an immutable empty set

frozenset(iterable) - > frozenset object Returns an immutable new set

iterable - the combined data type to be converted.

The above is the detailed content of Are python collections mutable?. 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