Home  >  Article  >  Backend Development  >  What are tuples and sets in python? Introduction to tuples and sets

What are tuples and sets in python? Introduction to tuples and sets

青灯夜游
青灯夜游forward
2018-10-19 16:24:044167browse

What this article brings to you is what are tuples and sets in python? An introduction to tuples and sets. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Friends who learn python often have this question. Since there is a list, why do we need tuples? Because lists are mutable and tuples are immutable. For example, we often need the data passed into the function to be unchanged. In this case, tuples are used.

def info(a):
    a[0] = 'haha'
    return a
a = [1,2,3]
info(a)
运行结果:['haha', 2, 3]

b = (1,2,3)
info(b)
运行结果:TypeError: 'tuple' object does not support item assignment

If you want to change the elements in the tuple, you can first convert the tuple into a list, and then convert it into a tuple after the elements are transformed. In fact, the object is recreated.

a = (1,2,3)
b = list(a)
b[0] = 5
a = tuple(b)
print(a)
运行结果:(5, 2, 3)

The collection has no sequence, and the elements inside are unique. Duplicate elements will be automatically eliminated.

Create a set:

  1. Use curly braces {}

  2. set()

#创建集合
a = set(['a',2,3])
print(a)
运行结果:{2, 3, 'a'}

b = set('abc')
print(b)
运行结果:{'a', 'b', 'c'}

Addition and removal of set elements:

a = set(['a',2,3])

#add添加
a.add('tong')#将整个元素添加进来
print(a)
运行结果:{'tong', 2, 3, 'a'}

#update添加
a.update('tong')#将字符串拆开添加进来
print(a)
运行结果:{'tong', 2, 3, 'n', 'a', 't', 'o', 'g'}

#集合元素的去除
a.remove('tong')
print(a)
运行结果:{2, 3, 'n', 'a', 't', 'o', 'g'}

Membership of sets:

a = set('abc')
'b' in a
运行结果:True

Intersection, union and difference of sets:

a = set('abc')
b = set('bcd')
print(a&b)#交集
print(a|b)#并集
print(a-b)#差集
运行结果:
{'c', 'b'}
{'d', 'a', 'b', 'c'}
{'a'}

Combine the collection to delete the elements in the list:

a = [1,2,3,1,3]
b = set(a)
print(b)
c = list(b)
print(c)
运行结果:
{1, 2, 3}
[1, 2, 3]

Freeze the collection:

#冻结集合
a = frozenset('abc')#集合则不可修改
a.add('d')
运行结果:AttributeError: 'frozenset' object has no attribute 'add'

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more related video tutorials, please visit: Python video tutorial, Python3 video tutorial, bootstrap video tutorial!

The above is the detailed content of What are tuples and sets in python? Introduction to tuples and sets. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete