A happy journey of simple Python: list operation of Python basic syntax

Defonds 2020-11-13 04:52:47
happy journey simple python list


List of articles


In the same series of blogs 《 Simple Python Happy journey :Python Examples of the use of cyclic keywords in basic syntax 》 We have made a preliminary understanding of the definition and use of list . This article will have a deeper understanding of its operation .
Python Lists allow you to hold heterogeneous types of elements . This is different from the list or array in other mainstream languages . but Python The list will suffice for all the requirements you may need an array . In this paper , We will learn the following : How to be in Python Create a list ; Access the elements in the list ; Find the number of elements in the list ; How to add a new element to the list ; How to delete an item from a list ; List element traversal ; Sort the list ; List inversion ; And more Python List transformation and aggregation operations .

1. Create an empty list

Python A list is a data structure that can store many different types of elements .
You can create an empty list by assigning empty brackets to variables .

mylist = []

1.1. Example : Create an empty list

In the next example , We create an empty list and check its data type .

cars = []
print(type(cars))
print(len(cars))

Execution and output :
 Create an empty list .png
Its length output is zero .

2. Access list elements

You can use the index as an array to access a list item individually . You can also use range index to access multiple list items .

mylist[5]
mylist[2:7]

If you want to traverse the list, please refer to : Loop list items .

2.1. Example : visit Python A single item in a list

You can access a single item by appending brackets and indexes to the list parameter name .
In the next example , We created one Python list , Then go to the third item . Because the index starts with 0, The third item in the index is 2.

# Access a single item of Python List
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
# access 3rd item with index 2
x = a[2]
print(x)
print(type(x))

Execution and output :
 visit Python A single item in a list .png

2.2. visit Python Multiple items in the list

By providing a range index , You can also sub list or multiple items of the list .
In the next example , We created an index , Then visit from page 2 To the first 5 term , Except for the total of three items indicated by the last index .

# Access a range of items in Python List
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
# access a range of items
x = a[1:4]
print(x)
print(type(x))

Execution and output :
 visit Python Multiple items in the list .png

3. List length

In fact, in this paper 1. The section has already used , Call the list as an argument Python We can get the length of the list .
Find the length of the list len() The function syntax is as follows :

len(listname)

This function returns the number of items in the list .
In the next example , We created a list , And then there's going to be len() Function finds the number of items contained in it .

# Python List Length
cars = ['Ford', 'Volvo', 'BMW', 'Tesla']
length = len(cars)
print('Length of the list is:', length)

Execution and output :
 List length .png

4. Additive elements

towards Python List adding elements use the append() function . Use append() The syntax of the function is as follows :

mylist.append(new_element)

new_element Is to append to the list mylist New elements in .

4.1. Example : Add new element to list

In the next example , We created a new list , And then add a new element to it .

# Python List – Append or Add Item
cars = ['Ford', 'Volvo', 'BMW', 'Tesla']
cars.append('Audi')
print(cars)

Execution and output :
 Additive elements .png

5. Remove elements

remove Python An item in a list can use the list object's remove() function , Using this method, the syntax is as follows :

mylist.remove(thisitem)

thisitem It's from mylist The one removed in .
remove() The function only removes the first occurrence of the item in the list , The rest will be retained . We'll also learn how to remove all items with specific values .

5.1. Remove elements that appear only once in the list

In the following example, we create a new list of elements , Then the elements that will only appear once 5 remove .

# Remove item that is present only once in the List
mylist = [21, 5, 8, 52, 21, 87]
item = 5
# remove the item
mylist.remove(item)
print(mylist)

Execution and output :
 Remove elements that appear only once in the list .png
You can see that the item has been removed , The index of each item after it is minus one .

5.2. Remove elements that appear more than once

In the next example , We created a new list of elements , And the item to remove 21, It appears twice in the list .

# Remove item that is present multiple times in the List
mylist = [21, 5, 8, 52, 21, 87]
item = 21
# remove the item
mylist.remove(item)
print(mylist)

Execution and output :
 Remove elements that appear more than once .png
It can be seen that although this item appears twice , But it's just the first one that's been removed .

5.3. Remove all items of elements that appear more than once

In this example , Our custom algorithm will appear more than once a given term 21 All delete .

# Remove all the occurrences of an item from the List
mylist = [21, 5, 8, 52, 21, 87]
item = 21
# remove the item for all its occurrences
for r_item in mylist:
if (item == r_item):
mylist.remove(item)
print(mylist)

Execution and output :
 Remove all items of elements that appear more than once .png

6. Remove an item that appears more than once in the list

There are three ways to remove a given item that appears more than once in the list .

  • Traverse the list and remove items that match the specified value .
  • Use lambda Function to filter out items that do not match the specified value .
  • Reuse remove() Method until the specified value does not exist in the list .
    The second method is recommended , Because it can provide better performance . The other two are just easy to understand .

6.1. Use for Circulation and remove() Remove method

Traverse the list , Once an item is found that matches the specified value , call remove() Method to remove . It was introduced in the previous section , No more details here .

6.2. Filter out all matches

Filter all items that do not match the specified value .

# Remove all occurrences in List using Filter
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# remove the item for all its occurrence
mylist = list(filter((r_item).__ne__, mylist))
print(mylist)
# Remove all occurrences in List using Filter
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# keep the item for all its occurrence
mylist = list(filter((r_item).__eq__, mylist))
print(mylist)

Execution and output :
 Filter out all matches .png

6.3. Use while Circulation and remove() Remove method

As long as the list contains a match , That is to remove the first item , Until there is no match .

# Remove all occurrences in List using While Loop
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# remove the item for all its occurrence
while r_item in mylist:
mylist.remove(r_item)
print(mylist)

Execution and output :
 Use while Circulation and remove() Remove method .png

7. List loop traversal

have access to for loop 、while Loop or enumeration to loop through the elements in the list . Next, we will introduce them one by one .
Take the list of heterogeneous data types as an example .

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

7.1. Use while Loop traversal

Use while Loop prints all the items in the list in turn .

# Loop List items using While Loop
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
i = 0
while i < len(a):
print(a[i])
print(type(a[i]))
i += 1

Execution and output :
 Use while Loop traversal .png

7.2. Use the index to traverse the list

for coordination range function , The traversal list can be accessed by index .

# Loop List items using index
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
for i in range(len(a)):
print(a[i])

Execution and output :
 Use the index to traverse the list .png
If you want to use the index when traversing, you can use this method .

7.3. Enhanced for loop

Or use enhanced for Loop no index direct access to the element itself .

# Loop List items accessing list item directly
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
for x in a:
print(x)

Execution and output :
 Enhanced for loop .png
If you don't need an index at your convenience, you can use this method .

7.4. Enumeration traverses list elements

Use enumeration , You can access elements and their indexes at the same time .

# Loop List items using Enumerate
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
for i, x in enumerate(a):
print('element#', i, 'is:', x)

Execution and output :
 Enumeration traverses list elements .png

8. Count the number of items with specified values in the list

To count how many times the specified value appears in the list , You can use the list of count() Tax included , Pass it the specified value as an argument .
In the next example, we create a new list , Then it looks up the number of times the specified value appears .

# Python – Count the items with a specific value in the List
mylist = [6, 52, 74, 62, 85, 62, 62, 85, 6, 92, 74]
length_74 = mylist.count(74)
length_62 = mylist.count(62)
length_92 = mylist.count(92)
length_73 = mylist.count(73)
print('74 occurred', length_74, 'times in the list')
print('62 occurred', length_62, 'times in the list')
print('92 occurred', length_92, 'times in the list')
print('73 occurred', length_73, 'times in the list')

Execution and output :
 Count the number of items with specified values in the list .png
count() The function only needs one parameter .

9. Append one list to another

Append one list to another , Use the... Of the list object extend() function .

list1.extend(list2)

A list of them list2 The elements in will be appended to the list list1.

9.1. Append list to another list

In the next example , We created two lists , Then add the second one to the first one .

# Append a list to another list
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
list1.extend(list2)
print(list1)

Execution and output :
 Append list to another list .png
list1 Has been modified ,list2 The content of is appended to the original element .## 9.2. Keep the original list , Add another list
If you want to keep the contents of the original list unchanged , Copy the list to a variable , Then append another list to the variable .

# Append a list to another list keeping a copy of original list
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
list = list1.copy()
list.extend(list2)
print(list)

Execution and output :
 Keep the original list , Add another list .png

10. Find the index of the element in the list

Pass the given value to the list class index() Method to find out where it first appears in the list .

index = mylist.index(item)

10.1. Find the index of an item in the list

Next we create a new list with numbers , Use index() Method we found the element 8 Index in the list .

# Find index when item is present in List
mylist = [21, 5, 8, 52, 21, 87]
item = 8
# search for the item
index = mylist.index(item)
print('The index of', item, 'in the list is:', index)

Execution and output :
 Find the index of an item in the list .png
The element appears in the third position , Or the index is 2.

10.2. Find the index of a multiple occurrence item in a list

Python The list allows the same element to appear more than once . In this case , Only the index of the first location is returned .

# Find index when item is present multiple times in List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 52
# search for the item
index = mylist.index(item)
print('The index of', item, 'in the list is', index)

Execution and output :
 Find the index of a multiple occurrence item in a list .png
Elements 52 It appears twice , But only the index of the first location is returned .

10.3. Find the index of items that do not appear in the list

If the element doesn't appear in the list , Use index() Function you will get a message that is item is not in list Of ValueError.

# Find Index when the specided Item is not present in List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 67
# search for the item
index = mylist.index(item)
print('The index of', item, 'in the list is', index)

Execution and output :
 Find the index of items that do not appear in the list .jpg

11. Inserts an element at the specified index

To add an element at the specified location or index , You can use Python Built in class list Of insert() Method .

mylist.insert(index, item)

In the specified index index Will be inserted at item Elements . The elements after the specified index are moved to the right in turn .

11.1. Inserts an element at the specified index

In the following example, we create a new list with numbers , And then we're indexing 4 Insert an element at 36.

# Insert Item at Specified Index in List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 4
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

Execution and output :
 Inserts an element at the specified index .jpg

11.2. Insert elements in the header of the list

In the following example, we will insert... At the beginning of the list 36. We need to provide an index 0 to insert() Method .

# Insert Item at Start of List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 0 # 1st position
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

Execution and output :
 Insert elements in the header of the list .jpg

11.3. Insert at the end of the list

In the following example, we'll insert... At the end of the list 36. We need to provide the index list length to insert() Method .

# Insert Item at End of List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = len(mylist)
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

Execution and output :
 Insert at the end of the list .jpg

11.4. Insert elements that are out of bounds in the array

If provided to insert() The index of the method exceeds the length of the list , The result is to append new elements to the end of the list .
Here is an example of an index provided that exceeds the length of the list .

# Insert Item with Index out of Bounds of List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 1000 # index out of bounds of list
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

Execution and output :
 Insert elements that are out of bounds in the array .png
contrary , If you provide a negative index , The new element will be inserted at the beginning of the list .

mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = -10 # index out of bounds of list
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

Execution and output :
 Negative index , The new element will be inserted at the beginning of the list .png

12. Remove the element at the specified index

To remove an element at a specified location or index , You can use built-in classes list Of pop() Method . The syntax of this method is as follows :

mylist.pop(index)

The index is optional . If you don't provide an index , The last element of the list will be removed .

12.1. Remove the element at the specified index

In the following example, we create a new list with numbers . We will use pop() Method to specify the index 3 Remove elements .

# Remove Item at Specific Index from List
mylist = [21, 5, 8, 52, 21, 87, 52]
index = 3
# delete item in mylist at index
mylist.pop(index)
print(mylist)

Execution and output :
 Remove the element at the specified index .png
The index for 3 The elements of 52 Has been removed .

12.2. Remove the last element of the list

To remove the last element of the list , Just don't pass any index to pop() The method can .

# Remove Last Item of List
mylist = [21, 5, 8, 52, 21, 87, 52]
# delete last item in mylist
mylist.pop()
print(mylist)

Execution and output :
 Remove the last element of the list .png

12.3. Pass an index that exceeds the length of the list to pop() Method

If you pass an index beyond the length of the list to pop() Method , You will get a message for pop index out of range Of IndexError.

# pop() method with index > length of list
mylist = [21, 5, 8, 52, 21, 87, 52]
index = 100 # index > length of list
mylist.pop(index)
print(mylist)

Execution and output :
 Pass the index that exceeds the length of the list .png

12.4. Pass a negative index to pop() Method

If you pass a negative value as an index to the pop() Method , The index will be considered a from 1 The starting reverse index .
such as , If you provide -1 As an index to pop(), The last element will be removed .
If you provide -3 to pop(), Last but not least 3 Elements will be deleted .
And if you give the absolute value of a negative index greater than the length of the list , You'll also get something like the example in the previous section IndexError.
In the next example , We use -2 To index to pop() Method , Last but not least 2 Elements will be removed .

# pop() with negative index
mylist = [21, 5, 8, 52, 21, 87, 52]
index = -2 # index < 0
mylist.pop(index)
print(mylist)

Execution and output :
 Pass negative index .png

13. List inversion

To reverse the order of all the elements in a list , Or the popular point will be called list reversal , You can use built-in classes list Of reverse() Method .
mylist.reverse()
Another way to reverse the list is to slice .
reversed_list = mylist[::-1]

13.1. Use reverse() Reverse list

In the next example , We created a list with numbers . And then we use reverse() Reverse it .

# Reverse List using reverse()
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.reverse()
print(mylist)

Execution and output :
 Use reverse() Reverse list .jpg
It can be seen that reverse() Is to modify the original list directly .

13.2. Use slices to reverse the list

Next we'll use slices to invert the list .

# Reverse List using Slicing
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist2 = mylist[ : : -1]
print(mylist)
print(mylist2)

Execution and output :
 Use slices to reverse the list .png
As you can see, slicing does not modify the original list , Only a new inverted list is returned .

13.3. Reverse the list of strings

Next, we reverse a list of strings .

# Reverse List of Strings
mylist = ['list', 'dict', 'set']
mylist.reverse()
print(mylist)

Execution and output :
 Reverse the list of strings .png

13.4. Application of list inversion

  • By reversing the list , You change the order in which the elements in the list are stored . If the elements in the list are already in positive order , So by reversing the list , You're going to get a reverse order .

14. Sort the list

To sort the list in positive or reverse order , You can use built-in classes list Of sort() Method .

mylist.sort(cmp=None, key=None, reverse=False)

among ,

  • cmp Define a custom comparison function , It requires two parameters , Return a negative number , Zero or positive , It depends on whether the first parameter is smaller than the second parameter , Equal or large . such as :cmp=lambda x,y: cmp(x.lower(), y.lower()).
  • key Defines a function , It has a parameter , Used to extract the comparison key from each list element :key=str.lower. The default value is None ( That is to compare the elements directly ).
  • reverse It's a Boolean value . If set to True, The list elements will be arranged in reverse order according to the comparison results .

14.1. Sort the list in positive order

Arrange the list in positive order , You just need to call the list object without passing in any parameters sort() Method . In the next example , We created a new list with numbers , Then we put the elements in a positive order .

# Sort a List in Ascending Order
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort()
print(mylist)

Execution and output :
 Sort the list in positive order .png
sort() The default behavior of the function is to sort the list elements in positive order .

14.2. Sort the list in reverse order

To sort the list in reverse order , It can deliver reverse=True Parameters to sort() function .

# Sort a List in Descending Order
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort(reverse=True)
print(mylist)

Execution and output :
 Sort the list in reverse order .png

15. Find the largest number in a list

You can use sort() Function or classic for Loop to find the largest number in a list . Use sort() Function is a concise way . But for the sake of learning, let's take a look at both ways .

15.1. Use sort() Function to find the maximum number

We know from the last section that sort() The function will arrange the elements of a list in positive or negative order . After you sort the list , If your list is in positive order, the largest number will be at the bottom of the list , And if you put it in reverse order, it will appear at the beginning of the list .

# Find the largest number using sort() function
a = [18, 52, 23, 41, 32]
a.sort()
a_len = len(a)
ln = a[a_len - 1]
print('Largest element is', ln)

Execution and output :
 Use sort() Function to find the maximum number .png

15.2. Use for Loop to find the maximum number

Although the use of sort() The function to find the maximum number looks simple , But use for Loop lookup can perform operations relatively quickly , Because it has fewer operations on the list .

# Find the largest number using for loop
a = [18, 52, 23, 41, 32]
ln = 0
for i in a:
if i > ln:
ln = i
print('Largest element is', ln)

Execution and output :
 Use for Loop to find the maximum number .png
In the example above , We created a new list , And assume that the maximum number is 0. And then we use for Loop through the list . During each iteration , We check that the maximum number is smaller than the current element . If so , We assign the current element to the maximum number . After the list traversal is finished , The number in the maximum number parameter is the largest number in the list .

16. Find the smallest number in a list

You can use sort() Function or classic for Loop to find the smallest number in a list . Use sort() Function is a concise way . But for the sake of learning, let's take a look at both ways .

16.1. Use sort() Function to find the smallest number

We know from the last section that sort() The function will arrange the elements of a list in positive or negative order . After you sort the list , If your list is in positive order, the smallest number will be at the beginning of the list , And if you put it in reverse order, it will appear at the bottom of the list .

# Find the smallest number using sort() function
a = [18, 52, 23, 41, 32]
a.sort()
sn = a[0]
print('Smallest element is', sn)

Execution and output :
 Use sort() Function to find the smallest number .png

16.2. Use for Loop to find the smallest number

Although the use of sort() The function looks very simple to find the smallest number , But use for Loop lookup can perform operations relatively quickly , Because it has fewer operations on the list .

# Find the smallest number using for loop
a = [18, 52, 23, 41, 32]
sn = float("inf")
for i in a:
if i < sn:
sn = i
print('Smallest element is', sn)

Execution and output :
 Use for Loop to find the smallest number .png
In the example above , We created a new list , And assume that the minimum number is infinite . And then we use for Loop through the list . During each iteration , We check that the minimum number is larger than the current element . If so , We assign the current element to the smallest number . After the list traversal is finished , The number in the minimum number parameter is the smallest number in the list .

Reference material

版权声明
本文为[Defonds]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database