current position:Home>Python Basics: do you know how to use lists?
Python Basics: do you know how to use lists?
2022-01-29 11:32:34 【Yunyun yyds】
Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .
list
Python There are four collection data types in :
- list : Is an ordered and variable ( Modifiable ) Set . Allow duplicate members .
- Tuples : Is orderly and cannot be changed or modified ( immutable ) Set . Allow duplicate members .
- Set: It's a disorder 、 An indexed and immutable collection , But we can add new items to the collection . Duplicate members are not allowed .
- Dictionaries : It's a disorder 、 variable ( Modifiable ) And index collection . There are no duplicate members .
The list is ordered and modifiable ( variable ) A collection of different data types . The list can be empty , You can also have items with different data types .
How to create a list
stay Python in , We can create lists in two ways :
- Use list built-in functions
# grammar
lst = list ()
Copy code
empty_list = list () # This is an empty list , There are no items in the list
print ( len ( empty_list )) # 0
Copy code
- Use square brackets ,[]
# grammar
lst = []
Copy code
empty_list = [] # This is an empty list , There are no items in the list
print ( len ( empty_list )) # 0
Copy code
List with initial values . We use len() To find the length of the list .
fruits = ['banana', 'orange', 'mango', 'lemon'] # Fruit list
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # List of vegetables
animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # List of animal products
web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # Network technology
countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
# Print the list and its length
print('Fruits:', fruits)
print('Number of fruits:', len(fruits))
print('Vegetables:', vegetables)
print('Number of vegetables:', len(vegetables))
print('Animal products:',animal_products)
print('Number of animal products:', len(animal_products))
print('Web technologies:', web_techs)
print('Number of web technologies:', len(web_techs))
print('Countries:', countries)
print('Number of countries:', len(countries))
Copy code
Output
Fruits: ['banana', 'orange', 'mango', 'lemon']
Number of fruits: 4
Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Number of vegetables: 5
Animal products: ['milk', 'meat', 'butter', 'yoghurt']
Number of animal products: 4
Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
Number of web technologies: 7
Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
Number of countries: 5
Copy code
- The list can contain items of different data types
lst = [ 'Asabeneh' , 250 , True , { 'country' : 'Finland' , 'city' : 'Helsinki' }] # Contains a list of different data types
Copy code
Use positive index to access list items
We use their indexes to access each item in the list , A list index from 0 Start , The following figure clearly shows where the index starts
fruits = ['banana', 'orange', 'mango', 'lemon']
first_fruit = fruits[0] # We use its index to access the first item
print(first_fruit) # Banana
second_fruit = fruits[1]
print(second_fruit) # The oranges
last_fruit = fruits[3]
print(last_fruit) # lemon
# The last index
last_index = len(fruits) - 1
last_fruit = fruits[last_index]
Copy code
Use negative index to access list items
A negative index means starting at the end ,-1 It means the last item ,-2 It means the penultimate term .
fruits = ['banana', 'orange', 'mango', 'lemon']
first_fruit = fruits[-4]
last_fruit = fruits[-1]
second_last = fruits[-2]
print(first_fruit) # Banana
print(last_fruit) # lemon
print(second_last) # Mango.
Copy code
Unpacking list items
lst = [ 'item' , 'item2' , 'item3' , 'item4' , 'item5' ]
first_item , second_item , third_item , * rest = lst
print ( first_item ) # item1
print ( second_item ) # item2
print ( third_item ) # item3
print( rest ) # ['item4', 'item5']
Copy code
# First example
fruits = [ 'banana' , 'orange' , 'mango' , 'lemon' , 'lime' , 'apple' ]
first_fruit , second_fruit , third_fruit , * rest = lst
print ( first_fruit ) # Banana
print ( second_fruit ) # Orange
print ( third_fruit ) # Mango.
print ( rest ) # ['lemon','lime','apple']
# The second example of unpacking list
first , second , third , * rest , tenth = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
print(first) # 1
print(second) # 2
print(third) # 3
print(rest) # [4,5,6,7,8,9]
print(tenth) # 10
# The third example is about unpacking list
countries = ['Germany', 'France','Belgium','Sweden','Denmark','Finland','Norway','Iceland','Estonia']
gr, fr, bg, sw, *scandic, es = countries
print(gr)
print(fr)
print(bg)
print(sw)
print(scandic)
print(es)
Copy code
Slice items from the list
- Positive index : We can start by specifying 、 End and step to specify a series of positive indexes , The return value will be a new list .( The default value for the start = 0, end = len(lst) - 1( Last item ), step = 1)
fruits = ['banana', 'orange', 'mango', 'lemon']
all_fruits = fruits[0:4] # It returns all the fruit
# This will also give the same result as the above one
all_fruits = fruits[0:] # If we don't set where to stop, it needs all the rest
orange_and_mango = fruits[1:3] # Excluding the first index
orange_mango_lemon = fruits[1:]
orange_and_lemon = fruits[::2] # Here we use the third parameter ,step. It will need every 2cnd term - ['banana', 'mango']
Copy code
- Negative index : We can start by specifying 、 End and step to specify a series of negative indexes , The return value will be a new list .
fruits = ['banana', 'orange', 'mango', 'lemon']
all_fruits = fruits[-4:] # It returns all the fruit
orange_and_mango = fruits[-3:-1] # It does not include the last index ,['orange', 'mango']
orange_mango_lemon = fruits[-3:] # This will start from -3 To end ,['orange', 'mango', 'lemon']
reverse_fruits = fruits[::-1] # A negative step will take the list in reverse order ,['lemon', 'mango', 'orange', 'banana']
Copy code
Modify the list
A list is an ordered collection of items that can be changed or modified . Let's modify the fruit list .
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits[0] = 'avocado'
print(fruits) # ['avocado', 'orange', 'mango', 'lemon']
fruits[1] = 'apple'
print(fruits) # ['avocado', 'apple', 'mango', 'lemon']
last_index = len(fruits) - 1
fruits[last_index] = 'lime'
print(fruits) # ['avocado', 'apple', 'mango', 'lime']
Copy code
Check the items in the list
Use in Operator to check whether an item is a member of a list . See the example below .
fruits = ['banana', 'orange', 'mango', 'lemon']
does_exist = 'banana' in fruits
print(does_exist) # really
does_exist = 'lime' in fruits
print(does_exist) # false
Copy code
Add item to list
To add an item to the end of an existing list , How we use append().
# grammar
lst = list ()
lst.append(item)
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.append('apple')
print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']
fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
print(fruits)
Copy code
Insert item into list
We can use insert() Method inserts a single item at the specified index in the list . Please note that , Other items move right . This plug-in () Method has two parameters : Index and insert items .
# grammar
lst = [ 'item1' , 'item2' ]
lst.insert(index, item)
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.insert(2, 'apple') # Insert an apple between an orange and a mango
print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']
fruits.insert(3, 'lime') # ['banana', 'orange', 'apple', 'lime', 'mango', 'lemon']
print(fruits)
Copy code
Remove items from the list
remove Method to delete the specified item from the list
# grammar
lst = [ 'item1' , 'item2' ]
lst.remove(item)
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon', 'banana']
fruits.remove('banana')
print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes the first occurrence of the item in the list
fruits.remove('lemon')
print(fruits) # ['orange', 'mango', 'banana']
Copy code
Use Pop Delete the project Pop up of () Method to delete the specified index ,( Or if the last item in the index is not specified ):
# grammar
lst = [ 'item1' , 'item2' ]
lst . pop () # Last item
lst.pop(index)
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.pop()
print(fruits) # ['banana', 'orange', 'mango']
fruits.pop(0)
print(fruits) # ['orange', 'mango']
Copy code
Title Use Del Delete the project
The delete keyword deletes the specified index and it can also be used to delete items within the index range . It can also completely delete the list
# grammar
lst = [ 'item1' , 'item2' ]
del lst [ index ] # There is only one project
del lst # Completely delete the list
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon', 'kiwi', 'lime']
del fruits[0]
print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime']
del fruits[1]
print(fruits) # ['orange', 'lemon', 'kiwi', 'lime']
del fruits[1:3] # # This will delete entries between the given indexes , Therefore, it will not delete the index as 3 Project !
print(fruits) # ['orange', 'lime']
del fruits
print(fruits) # This should be for :NameError: name “ Fruits ” No definition
Copy code
Clear list items
In a clear () Method to clear the list :
# grammar
lst = [ 'item1' , 'item2' ]
lst.clear()
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.clear()
print(fruits) # []
Copy code
Copy list
You can copy the list by reassigning the list to a new variable in the following ways :list2 = list1. Now? ,list2 It's right list1 References to , We are list2 Any changes made in will also modify the original list2, But in many cases , We don't like to modify the original version , But like to have different copies . One way to avoid these problems is to use copy().
# grammar
lst = [ 'item1' , 'item2' ]
lst_copy = lst . copy()
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits_copy = fruits.copy()
print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon']
Copy code
Join the list
stay Python There are many ways to connect or connect two or more lists .
- Plus operator (+)
# grammar
list3 = list1 + list2
Copy code
positive_numbers = [1, 2, 3, 4, 5]
zero = [0]
negative_numbers = [-5,-4,-3,-2,-1]
integers = negative_numbers + zero + positive_numbers
print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits_and_vegetables = fruits + vegetables
print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Copy code
- Use extend() Methods the connection extend() Method allows you to append a list to a list . See the example below .
# grammar
list1 = [ 'item1' , 'item2' ]
list2 = [ 'item3' , 'item4' , 'item5' ]
list1.extend(list2)
Copy code
num1 = [ 0 , 1 , 2 , 3 ]
num2 = [ 4 , 5 , 6 ]
num1.extend ( num2 )
print ( 'Numbers:' , num1 ) # Numbers: [0, 1, 2, 3, 4, 5, 6]
negative_numbers = [ - 5 , - 4 , - 3 , - 2 , - 1 ]
positive_numbers =[ 1 , 2 , 3 , 4 , 5 ]
zero = [ 0 ]
negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits.extend(vegetables)
print('Fruits and vegetables:', fruits ) # Fruits and vegetables : ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Copy code
Calculate items in the list
Count of () The number of times the item returned by the method is displayed in the list :
# grammar
lst = [ 'item1' , 'item2' ]
lst.count(item)
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
print(fruits.count('orange')) # 1
ages = [22, 19, 24, 25, 26, 24, 25, 24]
print(ages.count(24)) # 3
Copy code
Find the index of the item
The index of () Method returns the index of the item in the list :
# grammar
lst = [ 'item1' , 'item2' ]
lst.index(item)
Copy code
Fruits = [ 'banana' , 'orange' , 'mango' , 'lemon' ]
print ( fruits . index ( 'orange' )) # 1
ages = [ 22 , 19 , 24 , 25 , 26 , 24 , 25 , 24 ]
print(ages.index(24)) #2, First appearance
Copy code
Reverse list
In reverse () Method reverses the order of the list .
# grammar
lst = [ 'item1' , 'item2' ]
lst.reverse()
Copy code
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.reverse()
print(fruits) # ['lemon', 'mango', 'orange', 'banana']
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.reverse()
print(ages) # [24, 25, 24, 26, 25, 24, 19, 22]
Copy code
Sort list items
To sort the list , We can use sort() Method or sorted() Built in functions , This sort () Method to reorder the list items in ascending order , And modify the original list , If sort() Method parameters reverse be equal to true, It will sort the list in descending order .
- sort(): This method modifies the original list
# grammar
lst = [ 'item1' , 'item2' ]
lst . sort () # Ascending
lst . sort ( reverse = True ) # Descending
Copy code
Example :
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.sort()
print(fruits) # Sort alphabetically , ['banana', 'lemon', 'mango', 'orange']
fruits.sort(reverse=True)
print(fruits) # ['orange', 'mango', 'lemon', 'banana']
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.sort()
print(ages) # [19, 22, 24, 24, 24, 25, 25, 26]
ages.sort(reverse=True)
print(ages) # [26, 25, 25, 24, 24, 24, 22, 19]
Copy code
- sorted(): Return the sequence table without modifying the original list Example :
fruits = ['banana', 'orange', 'mango', 'lemon']
print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange']
# Reverse order
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits = sorted(fruits,reverse=True)
print(fruits) # ['orange', 'mango', 'lemon', 'banana']
Copy code
If it helps you in your study, you must keep it , More information about Python Learning experience , Tool installation package , E-book sharing , But I don't know , Pay attention to me , Continuous updating .
copyright notice
author[Yunyun yyds],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291132328631.html
The sidebar is recommended
- Quickly build Django blog based on function calculation
- Python interface test unittest usage details
- Implementation of top-level design pattern in Python
- You can easily get started with Excel. Python data analysis package pandas (VII): breakdown
- Using linear systems in python with scipy.linalg
- Together with Python to do a license plate automatic recognition system, fun and practical!
- Using linear systems in python with scipy.linalg
- Fast power modulus Python implementation of large numbers
- Quickly build Django blog based on function calculation
- You can easily get started with Excel pandas (I): filtering function
guess what you like
-
You can easily get started with Excel. Python data analysis package pandas (II): advanced filtering (I)
-
How does Python correctly call jar package encryption to get the encrypted value?
-
Python 3 interview question: give an array. If there is 0 in the array, add a 0 after 0, and the overall array length remains the same
-
Python simple Snake game (single player mode)
-
Using linear systems in python with scipy.linalg
-
Python executes functions and even code through strings! Come and understand the operation of such a top!
-
Decoding the verification code of Taobao slider with Python + selenium, the road of information security
-
[Python introduction project] use Python to generate QR code
-
Vanessa basks in her photos and gets caught up in the golden python. There are highlights in the accompanying text. She can't forget Kobe after all
-
[windows] Python installation pyteseract
Random recommended
- [introduction to Python project] create bar chart animation in Python
- Python series tutorials 116
- Practical series 1 ️⃣ Wechat applet automatic testing practice (with Python source code)
- [common links of Python & Python]
- [Python development tool Tkinter designer]: Lecture 1: introduction to the basic functions of Tkinter Designer
- [introduction to Python tutorial] use Python 3 to teach you how to extract any HTML main content
- Python socket implements UDP server and client
- Python socket implements TCP server and client
- leetcode 1974. Minimum Time to Type Word Using Special Typewriter(python)
- The mobile phone uses Python to operate picture files
- [learning notes] Python exception handling try except...
- Two methods of using pandas to read poorly structured excel. You're welcome to take them away
- Python sum (): the summation method of Python