The difference between set and list in python

silencement
Release: 2019-06-26 09:30:25
Original
4348 people have browsed it

The difference between set and list in python

A set is an unordered sequence of non-repeating elements.

You can use curly brackets { } or the set() function to create a set. Note: To create an empty set, you must use set() instead of { }, because { } is used to create an empty dictionary.

Creation format:

parame = {value01,value02,...}
或者set(value)
Copy after login

Example

>>>basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # 这里演示的是去重功能
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # 快速判断元素是否在集合内
True
>>> 'crabgrass' in basket
False
 
>>> # 下面展示两个集合间的运算.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # 集合a中包含而集合b中不包含的元素
{'r', 'd', 'b'}
>>> a | b                              # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # 集合a和b中都包含了的元素
{'a', 'c'}
>>> a ^ b                              # 不同时包含于a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'}
Copy after login

Use [] to create a list in python, and use subscript index to access the values ​​in the list. Similarly, you You can also use square brackets to intercept characters, as shown below:

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
 
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
Copy after login

Output result of the above example

list1[0]:  Google
list2[1:5]:  [2, 3, 4, 5]
Copy after login

The above is the detailed content of The difference between set and list in python. 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