Table of Contents
Basic format
Accessing list elements
Modify list elements
Add elements
Delete data in the list
List sorting
Use the reserse() method to flip the list elements
Use the len() method to get the length of the list
for loop traverses the list
Quickly assemble a number list
List generation formula
使用切片裁剪获取子列表
Home Backend Development Python Tutorial Basic learning of Python3 lists (with examples)

Basic learning of Python3 lists (with examples)

Dec 30, 2018 am 10:13 AM
python

The content of this article is about the basic learning of Python3 lists (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Foreword: Long time no see, I suddenly realized that I haven’t blogged for a long time. Recently, I am obsessed with Python and I can’t help myself. I learned about it. Python is simple and easy to learn, especially for those who have been exposed to Java. Getting started with Python is even better. The threshold is extremely low. In line with the principle of learning and recording, recording while learning is conducive to sorting out the learning results and also conducive to later review. Therefore, the first blog on the Python learning journey today is purely a record.

The simple syntax definition will not be recorded. Starting from the data structure, the most important thing in the program is to operate the data. To learn a programming language, you must undoubtedly master its unique data structure. Start now with List.

List is a data structure that is frequently used in Python programming. It consists of a series of elements arranged in a specific order, represented by [], with commas separating the elements, similar to an array in Java. Lists are created to store data, are dynamic, and crud operations can be performed on the list at any time. Since lists contain multiple elements, they are usually named in the plural form, such as names, letters, etc.

Basic format

fruits = ["apple","bananer","oranger"]
print(fruits)
Copy after login

Accessing list elements

Like most programming languages, access to python list data is also obtained through indexing. The first element is obtained from Starting from 0, the last element index is the total data sum of the list minus one. python also provides another special syntax. You can directly use -1 as the index to get the last element, and then subtract one to get the data in reverse. After obtaining the list data, you can directly use it to perform any operation.

print(fruits[0])//获取第一个元素 `apple`
print(fruits[-1])//获取最后一个元素`oranger`
Copy after login

Modify list elements

Get the element at the corresponding position directly according to the index and reassign it.

fruits[0] = "watermelon"//修改第一个元素
print(fruits)//重新打印列表
Copy after login

At this time the list changes to: ['watermelon', 'bananer', 'oranger']

Add elements

  • Call append() Method adds elements at the end of the list

fruits.append("Plum")
print(fruits)
Copy after login

At this time the list is: ['apple', 'bananer', 'oranger', 'Plum']

  • Call the insert() method to insert data at the specified index

fruits.insert(1,"pear")//在索引为1处插入数据
print(fruits)
Copy after login

The list at this time is: ['apple', 'pear', 'bananer', 'oranger']

Delete data in the list

  • If you know the index, directly use del to delete the data

del fruits[0]//删除第一个数据
print(fruits)
Copy after login

The list at this time is: ['pear', 'bananer', 'oranger']

  • Call pop() to pop up the list data and return the pop-up data. If no parameters are passed, the last element of the list will pop up by default. If the index value is passed, the specified index element will pop up

print(fruits.pop())//弹出最后一个元素,并打印
print(fruits)
print(fruits.pop(0))//弹出第一个元素,并打印
print(fruits)
Copy after login

Note that the result is:

oranger
['pear', 'bananer']
pear
['bananer']
Copy after login
  • If you do not know the index of the element and know the specific element value to be deleted, you can also directly call the remove() method to delete it. Note that after deletion, you can continue to use the element.

fruits = ["apple","bananer","oranger","prea"]
print(fruits)
delete = "bananer"//删除的元素
fruits.remove(delete)//调用方法删除指定元素值
print(fruits)
print(delete)//最后打印删除掉的元素
Copy after login

The result is:

['apple', 'bananer', 'oranger', 'prea']
['apple', 'oranger', 'prea']
bananer
Copy after login

List sorting

  • Call sort() to sort the list elements. The default is Natural order sorting. If you want to sort in reverse, you can pass in the parameter reverse=True. After sorting, the order of the list will be permanently changed.

fruits = ["bananer","apple","oranger","prea"]
print(fruits)
fruits.sort()
print(fruits)
Copy after login

The result is:

['bananer', 'apple', 'oranger', 'prea']
['apple', 'bananer', 'oranger', 'prea']
Copy after login
  • If we want to temporarily change the order of the list, we can use the sorted() method

fruits = ["bananer","apple","oranger","prea"]
print(fruits)
print(sorted(fruits))
print(fruits)
Copy after login

The result is:

['bananer', 'apple', 'oranger', 'prea']
['apple', 'bananer', 'oranger', 'prea']
['bananer', 'apple', 'oranger', 'prea']
Copy after login

It can be seen that the order of the list has not changed.

Use the reserse() method to flip the list elements

  fruits = ["bananer","apple","oranger","prea"]
  print(fruits)
  fruits.reverse()//翻转列表元素
  print(fruits)
Copy after login

The result is:

['bananer', 'apple', 'oranger', 'prea']
['prea', 'oranger', 'apple', 'bananer']
Copy after login

Use the len() method to get the length of the list

fruits = ["bananer","apple","oranger","prea"]
print(len(fruits))
Copy after login

The result is obviously 4.

for loop traverses the list

This is similar to java, the format is for xxx in list name:, after traversing to obtain the list data, we can Perform any operation

fruits = ["bananer","apple","oranger","prea"]
for fruit in fruits:
    print(fruit)
Copy after login

The result is to traverse and print out each element:

bananer
apple
oranger
prea
Copy after login

Note: There are no {} in code blocks in Python, and 4 spaces are used to indent the code. This is true for blocks, for loops, if loops, while loops, and method bodies. When writing code, be sure to pay attention to indentation

Quickly assemble a number list

ranger() The starting value and ending value can generate a series of numbers in order, and then use list() to quickly assemble a list of numbers in any range

numbers = list(range(1,6))//组装列表
print(numbers)
Copy after login

Result: [1, 2, 3, 4, 5] In fact, use traversal It can also be implemented, but this method is more convenient.

List generation formula

Use [expression for variable value in range(x,x) if xxx] to quickly generate a numerical list with just one statement, where the expression is the result of traversing the numerical value To operate, you can also add if conditions.

numbers = [x * x for x in range(1,6)]//求平方数值列表
print(numbers)
Copy after login

The result is: [1, 4, 9, 16, 25] This expression is quite concise, and the original several lines can be solved in one line.

使用切片裁剪获取子列表

使用 列表名[x:y] 裁剪获取对应索引区间的子列。假如省略起始值x,默认从0索引开始裁剪,假如省略结束值y,默认裁剪余下的所有元素。

fruits = ["bananer","apple","oranger","prea"]
print(fruits[0:2])
Copy after login

结果为:['bananer', 'apple']

至此,基本的列表操作差不多都总结完了,顺便记录一下元组

  • 列表中的数据是可变的,我们经常用它来存储可变的数据源

  • 元组跟列表一样也是用来存储数据源的,但是它存储的数据源是不可变的

  • 元组定义的格式也不一样,为(xxx,yyy,zzz).

  • 对于元组的操作,跟列表一样

The above is the detailed content of Basic learning of Python3 lists (with examples). 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)

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

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.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles