The number list is similar to other lists, but there are some functions that can make the operation of the number list more efficient. Let's create a list of 10 numbers and see what can be done.
# Print out the first ten numbers.
numbers =[1,2,3,4,5,6,7,8,9,10]for number in numbers:print(number)
range() function
The normal list creation method can create 10 numbers, but if you want to create a large number of numbers, this method is not suitable. The range() function helps us generate a large number of numbers. As follows:
# print the first ten number
for number inrange(1,11):print(number)
The parameters of the range() function include the start number and the end number. The resulting list of numbers contains the start number but not the end number. At the same time, you can also add a step parameter to tell the range() function how far the interval is. As follows:
# Print the first ten odd numbers.for number inrange(1,21,2):print(number)
If you want to convert the numbers obtained by the range() function to a list, you can use the list() function to convert. As follows:
# create a list of the first ten numbers.
numbers =list(range(1,11))print(numbers)
This method is quite powerful. Now we can create a list of the first million numbers, just as easy as creating a list of the first 10 numbers. As follows:
# Store the first million numbers in a list
numbers =list(range(1,1000001))
# Show the length of the list
print("The list 'numbers' has "+str(len(numbers))+" numbers in it.")
# Show the last ten numbers.print("\nThe last ten numbers in the list are:")for number in numbers[-10:]:print(number)
min(), max() and sum() functions
As the title indicates, you can apply these three functions to a list of numbers. The min() function finds the minimum value in the list, the max() function finds the maximum value, and the sum() function calculates the sum of all numbers in the list. As follows:
ages =[23,16,14,28,19,11,38]
youngest =min(ages)
oldest =max(ages)
total_years =sum(ages)print("Our youngest reader is "+str(youngest)+" years old.")print("Our oldest reader is "+str(oldest)+" years old.")print("Together, we have "+str(total_years)+" years worth of life experience.")
Knowledge point supplement:
range() function
In python, you can use the range() function to generate a series of numbers
for w inrange(1,11):print(w)
Output:
12345678910
# Note: here it ends at 10, excluding 11
So far, this article on how to understand the number list in python is introduced. For more detailed explanations of the number list in python, please search ZaLou.Cn
Recommended Posts