What is the syntax of python list derivation
Editor to share with you what is the grammar of python list derivation. I hope you will gain something after reading this article. Let's discuss it together.
List derivation
List derivation can replace annoying loops in list filling, and its basic syntax is
[expression for item in list if conditional]
Let's look at a very basic example of populating a list with a sequence of numbers:
Mylist = [i for i inrange (10)] print (mylist) # [0, 1, 2, 3, 4,5,6,7,8,9]
Because you can use expressions, you can also do some mathematical operations:
Squares = [x**2for x inrange (10)] print (squares) # [0,1,4,9 people 16, 25, 36, 49, 64, 81]
You can even call external functions:
Defsome_function (a): return (a + 5) / 2 my_formula= [some_function (I) for i inrange (10)] print (my_formula) # [2.5,3.0 dint 3.5,4.0 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
Finally, you can use the if function to filter the list. In this case, only values that are divisible by 2 are retained:
Filtered = [i for i inrange (20) if I% 2 examples 0] print (filtered) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] after reading this article, I believe you have a certain understanding of "what is the grammar of python list derivation". If you want to know more related knowledge, welcome to follow the industry information channel, thank you for reading!