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]
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 = []
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
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
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, 'China', 19.998] >>> print L[-1]19.998
-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
>>>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, 'China', 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']
>>>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() 'Jack' >>> print L [12, 3.14, 'China', 19.998] >>> L.pop(0) >>> print L [3.14, 'China', 19.998]
You can also copy and replace through subscripts
>>> L[1] = 'America' >>> print L [3.14, 'America', 19.998]
set:
set is also a set of numbers, unordered, and the content cannot be repeated. By calling set( ) method creation:
>>> s = set(['A', 'B', 'C'])
The meaning of accessing a set is just to check whether an element is in the set. Pay attention to case sensitivity:
>>> print 'A' in s True >>> print 'D' in s False
Also traverse through for:
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])
for x in s:
print x[0],':',x[1]
>>>
Lisa : 85
Adam : 95
Bart : 59Add 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])
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])
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])
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
So if we want to determine whether an element meets some different conditions, using set is the best choice. The following example:
months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',])
x1 = 'Feb'
x2 = 'Sun'
if x1 in months:
print 'x1: ok'
else:
print 'x1: error'
if x2 in months:
print 'x2: ok'
else:
print 'x2: error'
>>>
x1: ok
x2: errorIn 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!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
SQLAlchemy 2.0 Deprecation Warning and Connection Close Problem Resolving Guide
Aug 05, 2025 pm 07:57 PM
This article aims to help SQLAlchemy beginners resolve the "RemovedIn20Warning" warning encountered when using create_engine and the subsequent "ResourceClosedError" connection closing error. The article will explain the cause of this warning in detail and provide specific steps and code examples to eliminate the warning and fix connection issues to ensure that you can query and operate the database smoothly.
How to automate data entry from Excel to a web form with Python?
Aug 12, 2025 am 02:39 AM
The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.
python pandas styling dataframe example
Aug 04, 2025 pm 01:43 PM
Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,
How to create a virtual environment in Python
Aug 05, 2025 pm 01:05 PM
To create a Python virtual environment, you can use the venv module. The steps are: 1. Enter the project directory to execute the python-mvenvenv environment to create the environment; 2. Use sourceenv/bin/activate to Mac/Linux and env\Scripts\activate to Windows; 3. Use the pipinstall installation package, pipfreeze>requirements.txt to export dependencies; 4. Be careful to avoid submitting the virtual environment to Git, and confirm that it is in the correct environment during installation. Virtual environments can isolate project dependencies to prevent conflicts, especially suitable for multi-project development, and editors such as PyCharm or VSCode are also
How to implement a stack data structure using a list in Python?
Aug 03, 2025 am 06:45 AM
PythonlistScani ImplementationAking append () Penouspop () Popopoperations.1.UseAppend () Two -Belief StotetopoftHestack.2.UseP OP () ToremoveAndreturnthetop element, EnsuringTocheckiftHestackisnotemptoavoidindexError.3.Pekattehatopelementwithstack [-1] on
python schedule library example
Aug 04, 2025 am 10:33 AM
Use the Pythonschedule library to easily implement timing tasks. First, install the library through pipinstallschedule, then import the schedule and time modules, define the functions that need to be executed regularly, then use schedule.every() to set the time interval and bind the task function. Finally, call schedule.run_pending() and time.sleep(1) in a while loop to continuously run the task; for example, if you execute a task every 10 seconds, you can write it as schedule.every(10).seconds.do(job), which supports scheduling by minutes, hours, days, weeks, etc., and you can also specify specific tasks.
How to handle large datasets in Python that don't fit into memory?
Aug 14, 2025 pm 01:00 PM
When processing large data sets that exceed memory in Python, they cannot be loaded into RAM at one time. Instead, strategies such as chunking processing, disk storage or streaming should be adopted; CSV files can be read in chunks through Pandas' chunksize parameters and processed block by block. Dask can be used to realize parallelization and task scheduling similar to Pandas syntax to support large memory data operations. Write generator functions to read text files line by line to reduce memory usage. Use Parquet columnar storage format combined with PyArrow to efficiently read specific columns or row groups. Use NumPy's memmap to memory map large numerical arrays to access data fragments on demand, or store data in lightweight data such as SQLite or DuckDB.
python logging to file example
Aug 04, 2025 pm 01:37 PM
Python's logging module can write logs to files through FileHandler. First, call the basicConfig configuration file processor and format, such as setting the level to INFO, using FileHandler to write app.log; secondly, add StreamHandler to achieve output to the console at the same time; Advanced scenarios can use TimedRotatingFileHandler to divide logs by time, for example, setting when='midnight' to generate new files every day and keep 7 days of backup, and make sure that the log directory exists; it is recommended to use getLogger(__name__) to create named loggers, and produce


