Home Backend Development Python Tutorial The difference between list and set in Python

The difference between list and set in Python

Jul 05, 2019 am 11:00 AM

The difference between list and set in Python

list:

literally means a collection. In Python, elements in a List are represented by square brackets []. You can define a List like this:

L = [12, 'China', 19.998]
Copy after login

You can see that the types of elements are not required to be the same. Of course, you can also define an empty List:

L = []
Copy after login

The List in Python is ordered, so if you want to access the List, you must obviously access it through the serial number, just like the subscript of the array, it is the same as the subscript Starting from 0:

>>> print L[0]12
Copy after login

Do not cross the boundary, otherwise an error will be reported

>>> print L[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
Copy after login

List can also be accessed in reverse order, and the serial number is represented by a subscript such as "the x-th from the bottom", such as -1 This subscript represents the penultimate element:

>>> L = [12, &#39;China&#39;, 19.998]
>>> print L[-1]19.998
Copy after login

-4 is obviously out of bounds, as follows:

>>> print L[-4]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print L[-4]
IndexError: list index out of range
>>>
Copy after login

List is added to the end through the built-in append() method, and insert () method is added to the specified position (the subscript starts from 0):

>>> L = [12, &#39;China&#39;, 19.998]
>>> L.append('Jack')
>>> print L
[12, 'China', 19.998, 'Jack']
>>> L.insert(1, 3.14)
>>> print L
[12, 3.14, 'China', 19.998, 'Jack']
>>>
Copy after login

Note that there are several methods in python that are similar to append, but the effects are completely different. When using them, you need to choose the correct method according to actual needs

1. append() Appends a new element to the end of the list. The list only occupies one index position and adds it to the original list.

2. extend() Appends a list to the end of the list and adds the elements in the list to the end of the list. Each element of is appended, and

is added to the original list. For example, list1=[1, 2, 3] .list2=[4, 5, 6]

list1.append(list2 ) The result is [1, 2, 3, [4, 5, 6]]

The result of list1.extend(list2) is [1, 2, 3, 4, 5, 6]

3. Using the number directly seems to have the same effect as using extend(), but it actually generates a new list to store the sum of the two lists. It can only be used to add the two lists.

4. = The effect is the same as extend(). It adds a new element to the original list and adds it to the original list.

Delete the last tail element through pop(). You can also specify a parameter to delete the specified position:

>>> L.pop()
&#39;Jack&#39;
>>> print L
[12, 3.14, &#39;China&#39;, 19.998]
>>> L.pop(0)
>>> print L
[3.14, &#39;China&#39;, 19.998]
Copy after login

You can also copy and replace through subscripts

>>> L[1] = &#39;America&#39;
>>> print L
[3.14, &#39;America&#39;, 19.998]
Copy after login

set:

set is also a set of numbers, unordered, and the content cannot be repeated. By calling set( ) method creation:

>>> s = set([&#39;A&#39;, &#39;B&#39;, &#39;C&#39;])
Copy after login

The meaning of accessing a set is just to check whether an element is in the set. Pay attention to case sensitivity:

>>> print &#39;A&#39; in s
True
>>> print &#39;D&#39; in s
False
Copy after login

Also traverse through for:

s = set([(&#39;Adam&#39;, 95), (&#39;Lisa&#39;, 85), (&#39;Bart&#39;, 59)])

for x in s:
    print x[0],&#39;:&#39;,x[1]

>>>
Lisa : 85
Adam : 95
Bart : 59
Copy after login

Add and delete elements through add and remove (keep them non-repeating). When adding elements, use the add() method of set

>>> s = set([1, 2, 3])
>>> s.add(4)
>>> print s
set([1, 2, 3, 4])
Copy after login

If the added element already exists in the set, add( ) will not report an error, but it will not be added:

>>> s = set([1, 2, 3])
>>> s.add(3)
>>> print s
set([1, 2, 3])
Copy after login

When deleting elements in the set, use the remove() method of the set:

>>> s = set([1, 2, 3, 4])
>>> s.remove(4)
>>> print s
set([1, 2, 3])
Copy after login

If the deleted element does not exist in the set, remove() will report an error:

>>> s = set([1, 2, 3])
>>> s.remove(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4
Copy after login

So if we want to determine whether an element meets some different conditions, using set is the best choice. The following example:

months = set([&#39;Jan&#39;,&#39;Feb&#39;,&#39;Mar&#39;,&#39;Apr&#39;,&#39;May&#39;,&#39;Jun&#39;,&#39;Jul&#39;,&#39;Aug&#39;,&#39;Sep&#39;,&#39;Oct&#39;,&#39;Nov&#39;,&#39;Dec&#39;,])
x1 = &#39;Feb&#39;
x2 = &#39;Sun&#39;

if x1 in months:
    print &#39;x1: ok&#39;
else:
    print &#39;x1: error&#39;

if x2 in months:
    print &#39;x2: ok&#39;
else:
    print &#39;x2: error&#39;

>>>
x1: ok
x2: error
Copy after login

In addition, the calculation efficiency of set is higher than that of list.

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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

See all articles