Collection is another importantPythondata structure.
We can say that they work like tuples, but they are not ordered, they areVolatile. Or we can say that they work like dictionaries, but they have no keys.
They also have an unchanging version calledfrozenset
.
You can create a collection using the following syntax:
names = {"Roger", "Syd"}
When you think of sets as mathematical sets, they work well.
You can intersect two sets:
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
intersect = set1 & set2 #{‘Roger’}
You can create the union of two sets:
set1 = {"Roger", "Syd"}
set2 = {"Luna"}
union = set1 | set2
#{‘Syd’, ‘Luna’, ‘Roger’}
You can get the difference between the two groups:
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
difference = set1 - set2 #{‘Syd’}
You can check whether a set is a superset of another set (of course, if one set is a subset of another set)
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
isSuperset = set1 > set2 # True
you can use itlen()
Global functions:
names = {"Roger", "Syd"}
len(names) # 2
You can get a list of items in the collection by passing the collection to the collection.list()
Constructor:
names = {"Roger", "Syd"}
list(names) #['Syd', 'Roger']
you can use itin
operator:
print("Roger" in names) # True
More python tutorials:
- Introduction to Python
- 在macOS上安装Python 3
- Run Python program
- Python 2 and Python 3
- Basics of using Python
- Python data types
- Python operators
- Python string
- Python boolean
- Python numbers
- Python, accepts input
- Python control statements
- Python list
- Python tuple
- Python set
- Python dictionary
- Python functions
- Python objects
- Python loop
- Python module
- Python class
- Python standard library
- Debug Python
- Python variable scope
- Python, accept parameters from the command line
- Python recursion
- Python nested functions
- Python Lambda function
- Python closure
- Python virtual environment
- Use Python to use GoPro as a remote webcam
- Python, how to create a list from a string
- Python decorator
- Python Docstrings
- Python introspection
- Python notes
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get detailed information of a file
- Python, how to check if a file or directory exists
- Python exception
- Python, how to create a directory
- Python, how to create an empty file
- Python, `with` statement
- Python, create a network request
- Python, use `pip` to install third-party software packages
- Python, read file content