Home Backend Development Python Tutorial What are sets in Python? Simple collection operations

What are sets in Python? Simple collection operations

Jan 19, 2019 pm 04:40 PM
python gather

What are sets in Python? This article will introduce you to Python collections and how to perform simple operations on collections. I hope it will be helpful to you.

#What are sets in Python?

In Python, a set is an unordered sequence of non-repeating elements. It is iterable and has no duplicate elements (each element is unique). [Recommended related video tutorials: Python Tutorial]

The collection of Python is similar to the collection of mathematical concepts, with the following additional conditions:

○ Collection The elements in cannot be repeated.

○ The elements in the collection are immutable (cannot be modified), but the entire collection is mutable.

○ No index is attached to any element in the python set. Therefore, they do not support any indexing or slicing operations.

Note:

1. Sets in python are usually used for mathematical operations, such as union, intersection, comparison, etc.

2. The main advantage of using a set compared to a list is that it has a highly optimized method for checking whether a specific element is contained in the set.

Simple operations of collections

1. Create a collection

You can use curly brackets { } Or use 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.

Example: Create a set by using the set() function or by placing all elements in a pair of curly braces. Notice how the order of the elements in the result changes.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
Copy after login

Output:

What are sets in Python? Simple collection operations

2. Access the values ​​in the collection

We cannot access a single value in the collection value, only all elements can be accessed. A list of individual elements can be obtained by looping through the collection. Example:

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days:
print(d)
Copy after login

Output:

What are sets in Python? Simple collection operations

3. Add elements

Use the add() method to add elements Add to collection

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
print(Days)
Days.add("Sun")
print(Days)
Copy after login

Output:

What are sets in Python? Simple collection operations

4. Remove elements

Use discard() method Remove elements from the collection. Example:

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
print(Days)
Days.discard("Tue")
print(Days)
Copy after login

Output:

What are sets in Python? Simple collection operations

5. Merge two collections

can be on both collections Performing a union operation produces a new set containing all the distinct elements from both sets. Example:

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print("A集合 ",DaysA)
print("\n")
print("B集合",DaysB)
print("\n")
print("A,B的并集:",AllDays)
Copy after login

Output:

What are sets in Python? Simple collection operations

In the above example, the element "Wed" appears in both collections, but in the new collection it will only There is one.

6. Find the same elements of two collections

You can perform an intersection operation on two collections, and a new collection will be generated, which only contains elements from the two collections. public elements. Example:

DaysA = set(["Mon","Tue","Wed","Sun"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print("A集合 ",DaysA)
print("\n")
print("B集合",DaysB)
print("\n")
print("A,B的交集:",AllDays)
Copy after login

Output:

What are sets in Python? Simple collection operations

7. Calculate the number of set elements

Use len () method to calculate the number of elements in the set, for example:

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
print("\n")
print("A集合:",DaysA)
print("元素个数为:",len(DaysA))
print("\n")
print("B集合:",DaysB)
print("元素个数为:",len(DaysB))
Copy after login

Output:

What are sets in Python? Simple collection operations

8. Determine whether the specified element exists in the set

You can use the operator in to determine whether the specified element exists in the collection. It will return True if it exists and False if it does not exist.

Example: Determine whether the elements "Runoob" and "Fri" are in the set Days

Days = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
x="Runoob" in Days
y="Fri" in Days
print(x)
print("\n")
print(y)
Copy after login

Output:

What are sets in Python? Simple collection operations

9. Clear the collection

You can use clear() to clear the collection, for example:

Days = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])

print(Days.clear())
Copy after login

Output:

What are sets in Python? Simple collection operations

The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of What are sets in Python? Simple collection operations. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles