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

Are collections mutable in python?

(*-*)浩
(*-*)浩Original
2019-08-01 10:18:093656browse

A collection is an unordered collection of different elements. Unlike sequence types (such as lists, strings, etc.), collections do not have slicing operations.

Are collections mutable in python?

Python collections are divided into two types: (Recommended learning: Python video tutorial)

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

frozenset - Immutable collection, the elements in the collection cannot be changed.

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.

rozenset() function

Description: You can convert other combined data types into immutable collection types (or convert mutable collection type set into immutable The collection type frozenset) returns an immutable collection with no duplicate elements and an arbitrary order.

Syntax:

frozenset() -> empty frozenset object  返回一个不可变空集合
frozenset(iterable) -> frozenset object  返回一个不可变新集合

iterable - the combined data type to be converted.

Program example:

s1 = frozenset() #创建一个不可变的空集合。
l = [1.23,"a"] #列表类型
d = {1:"a",2:"b"} #字典类型
a = (1,2,"b") #元组类型
s = "厉害了,我的国" #字符串
c = set("1,2,3a") #可变集合
 
#将列表,字典,元组,字符串 可变集合 转化为不可变集合
s2 = frozenset(s)
s3 = frozenset(l) 
s4 = frozenset(d)
s5 = frozenset(a)
s6 = frozenset(c) #将可变集合转换为不可变集合s6
 
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(s6)

For more Python-related technical articles, please visit the Python Tutorial column to learn!

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