List of operations in python

Posted by spasm37 on Wed, 22 Dec 2021 19:45:09 +0100

catalogue

1, Traverse the entire list (for loop)

2, Avoid indenting errors

3, Create a list of values

4, Use part of the list

5, Tuple

1, Traverse the entire list (for loop)

It is often necessary to traverse all elements of the list. If you need to perform the same operation on each element in the list, you can use the for loop in python. Colon at the end of the for statement: don't omit. The print() after the for statement needs to be indented.

If there is a long list of magicians, print out the list of each magician. If each name is obtained separately, it will include a large number of duplicate codes. At the same time, if the length of the list changes, the code needs to be modified. Therefore, the for loop is used.

magicians=['alice','david','carolina']
for magician in magicians:   #First define the loop, take a name from the magicians list and associate it with magician
	print(magician)
alice
david
carolina

1. Simply understand the for loop

Python first reads the first line of code for magician in magicians -- let Python get the first value 'alice' in the list magicians and associate it with the variable magician. Next, python reads the next line of code print(magician) -- let Python print its value. Since the list contains other values, python returns to the first line of the loop until there is no other code after the for loop.

Each element in the list will perform the steps specified in the loop, no matter how many elements the list contains. Using singular and plural names can help you determine whether the code snippet is dealing with a single list element or an entire list. For example, for dog in dogs Each indented line of code is part of a loop that is executed once for each value in the list.

2. Do more in the for loop

magicians=['alice','david','carolina']
for magician in magicians: 
	print(f'{magician.title()},that was a great trick!')
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
magicians=['alice','david','carolina']
for magician in magicians: 
	print(f'{magician.title()},that was a great trick!')
	print(f"I can't wait to see your next trick,{magician.title()}!\n") #Insert blank lines after each iteration
	#Both function calls print() are indented, so they will be executed once for each magician in the list.
Alice,that was a great trick!
I can't wait to see your next trick,Alice!

David,that was a great trick!
I can't wait to see your next trick,David!

Carolina,that was a great trick!
I can't wait to see your next trick,Carolina!

3. Perform some operations after the for loop

magicians=['alice','david','carolina']
for magician in magicians: 
	print(f'{magician.title()},that was a great trick!')
	print(f"I can't wait to see your next trick,{magician.title()}!\n") #Insert blank lines after each iteration
	#Both function calls print() are indented, so they will be executed once for each magician in the list.
print("Thank you,everyone.That was a great magic show!")
#The third call print is not indented, so it is only executed once. If indented, it will be repeated 3 times.
Alice,that was a great trick!
I can't wait to see your next trick,Alice!

David,that was a great trick!
I can't wait to see your next trick,David!

Carolina,that was a great trick!
I can't wait to see your next trick,Carolina!

Thank you,everyone.That was a great magic show!

Both function calls print() are indented, so they will be executed once for each magician in the list. The third call print is not indented, so it is only executed once.

2, Avoid indenting errors

python judges the relationship between the code line and the previous code line according to indentation. Indentation can make the code neat and clear.

1. Forget the indentation: the code line immediately after the for statement does not have indentation when calling print().                               

 IndentationError: expected an indented block

2. Forget to indent additional lines of code: it can run without error, but the result is unexpected and there are logical errors.

magicians=['alice','david','carolina']
for magician in magicians: 
	print(f'{magician.title()},that was a great trick!')
print(f"I can't wait to see your next trick,{magician.title()}!\n") 
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
I can't wait to see your next trick,Carolina!

3. Unnecessary indentation: only the code to be executed on each element in the for loop needs indentation.

IndentationError: unexpected indent

4. Unnecessary indentation after cycle: it can run without error, but the result is unexpected and there is a logic error.

magicians=['alice','david','carolina']
for magician in magicians: 
	print(f'{magician.title()},that was a great trick!')
	print(f"I can't wait to see your next trick,{magician.title()}!") 
	print("Thank you,everyone.That was a great magic show!")
Alice,that was a great trick!
I can't wait to see your next trick,Alice!
Thank you,everyone.That was a great magic show!
David,that was a great trick!
I can't wait to see your next trick,David!
Thank you,everyone.That was a great magic show!
Carolina,that was a great trick!
I can't wait to see your next trick,Carolina!
Thank you,everyone.That was a great magic show!

5. Missing colon: it will lead to syntax error. Python doesn't know what you want. The colon at the end of the for statement tells python that the next line is the first line of the loop.

magicians=['alice','david','carolina']
for magician in magicians
	print(magician)
SyntaxError: invalid syntax

3, Create a list of values

1. Use the function range()

The range function can easily generate a series of numbers. The function range () causes python to count from the first value specified and stop at the second value specified, which is the result of the common differential behavior in programming languages. When calling the function range(), you can also specify only one parameter so that it will start at 0.

for value in range(1,5):
	print(value)
1
2
3
4
for value in range(5):
	print(value)
0
1
2
3
4

2. Create a list of numbers using range()

To create a list of numbers, you can use the function list() to turn the result of range() directly into a list. Only the function range() will print out a series of numbers. To convert the numbers into a list, you can use list().

numbers=(list(range(1,6)))
print(numbers)
[1, 2, 3, 4, 5]

! The difference between 1 and 2: 1 traverses a series of numbers with the for loop, so each line printed out is a number. 2 list() is used, so it is a list of numbers, so the list needs a list name.

Use the range() function to specify the step size. Therefore, you can specify a third parameter to this function, and python generates numbers according to the step size

even_numbers=list(range(2,11,2)) #Starting from 2, the final value is less than 11, and continue to add 2
print(even_numbers)
[2, 4, 6, 8, 10]

Using range(), you can create almost any number set you need, such as a list of squares of 1-10, * * represents a power operation. You don't have to use list() to create a list. You can create an empty list first and attach it in a loop.

squares=[]
for value in range(1,11):    #Expand the for loop and first take out the first number 1
	square=value**2          #Square the first number 1 and associate it with square
	squares.append(square)   #Append the square number to the list and carry out the next cycle until 10 in the list is executed
	#Lines 3 and 4 are equivalent to squares append(value**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3. Perform simple statistical calculations on the list of numbers

Find the maximum value: function max(); Find the minimum value: function min(); Summation: function sum().

>>> digits=[1,2,3,4,5,6,7,8,9,0]
>>> max(digits)
9
>>> min(digits)
0
>>> sum(digits)
45

4. List analysis

The previous method of generating squares contains three or four lines of code, while list parsing only needs to write one line of code.

List parsing combines the for loop and the code that creates the new element into one line, and automatically attaches the new element.

First, specify a descriptive list name (squares), specify the left parenthesis, define an expression to generate the value to be stored in the list (value**2), and write a for loop to provide the value to the expression (for value in range(1,11), plus a right parenthesis. Note: there is no colon at the end of the for statement.

squares=[value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4, Use part of the list

1. Slice

Some elements of the processing list are called slices. To create a slice, you need to specify the index of the first element and the last element, separated by a colon. python stops after reaching the element before the second index. The output is a list.

players=['charles','martina','michael','florence','eli']
print(players[0:3])
['charles', 'martina', 'michael']

If the first index is not specified, python automatically starts at the beginning of the list.

players=['charles','martina','michael','florence','eli']
print(players[:4])
['charles', 'martina', 'michael', 'florence']

Let the slice terminate at the end of the list without specifying a second index. Negative index can also be used to output the slice at the end of the list.

players=['charles','martina','michael','florence','eli']
print(players[1:])  #From the second element to the last
print(players[-2:]) #From the penultimate element to the last
['martina', 'michael', 'florence', 'eli']
['florence', 'eli']

2. Traverse slices

To traverse some elements of the list, you can use slicing in the for loop.

players=['charles','martina','michael','florence','eli']
print("Here is the first three players on my team.")
for player in players[:3]:    #Traverse the top 3 players
	print(player)
Here is the first three players on my team.
charles
martina
michael

3. Copy list

Copy list: you can create a slice containing the whole list by omitting both the start and end indexes ([:]), that is, a copy of the whole list.

List copied when using slices: you get two different lists because slices create a copy of the list.

my_foods=['cake','dessert','milk']
friend_foods=my_foods[:]  #Extract the slice, create a copy of the list, and assign the copy to the variable friend_foods.
my_foods.append('apple')
friend_foods.append('orange')
print(f"My favorite foods are {my_foods}.")
print(f"My friend's favorite foods are {friend_foods}.")
My favorite foods are ['cake', 'dessert', 'milk', 'apple'].
My friend's favorite foods are ['cake', 'dessert', 'milk', 'orange'].

List copied without slice: only one list will be obtained because of association.

my_foods=['cake','dessert','milk']
friend_foods=my_foods    
#Not my_ Give a copy of foods to friend_food, but friends_ Foods and my_foods Association, so only one list is generated.
friend_foods.append('orange')
print(f"My favorite foods are {my_foods}.")
print(f"My friend's favorite foods are {friend_foods}.")
My favorite foods are ['cake', 'dessert', 'milk', 'apple', 'orange'].
My friend's favorite foods are ['cake', 'dessert', 'milk', 'apple', 'orange'].

! Note: when using a copy of the list, the results are unexpected. Confirm whether the list is copied using slices.

5, Tuple

Lists are very useful for storing data sets that may change during program operation, because lists can be modified.

However, sometimes it is necessary to create a series of immutable elements, and tuples can meet this requirement. python calls immutable values immutable and immutable lists tuples. Tuples are simpler data structures than lists. Tuples can be used if the stored values remain unchanged throughout the life cycle of the program.

1. Define tuples

Tuples look like lists, but are identified by parentheses () instead of brackets []. After defining tuples, elements can be accessed by indexes.

dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
200
50

An attempt to modify a tuple returns a type error message.  

dimensions=(200,50)
dimensions[0]=250 #Attempt to modify tuple element
TypeError: 'tuple' object does not support item assignment

Note: strictly speaking, tuples are identified by commas. Parentheses just make the list look cleaner. If you define tuples that include only one element, you must add commas after the element. Such as my_t=(3,)

2. Traverse all values in tuple

You can use the for loop to traverse all values in the tuple.

dimensions=(200,50)
for dimension in dimensions:
	print(dimension)
200
50

3. Modify tuple variable

Although the element of the tuple cannot be modified, the variable storing the tuple can be assigned a value,

dimensions=(200,50)
print('Original dimension:')
for dimension in dimensions:
	print(dimension)
dimensions=(400,100)   #Associate a new meta group to the variable dimensions
print('Modified dimension:')
for dimension in dimensions:
	print(dimension)
Original dimension:
200
50
Modified dimension:
400
100

Topics: Python list