Although a numerical list can be created manually by filling each element within square brackets in Python, very often will the analyst use some type of ready functions. For example in the following code example, we first try using a for loop with a range() function to print out number 1,2,3,4, then use list() combined with range() function to get the same result.
#print out 10,11,12,13,14 using a for loop and range() function
for nr in range(10,15):
print(nr)
#output
10
11
12
13
14
#using list() and range() to create a numerical list,
#then print out elements of the list
numbers = list(range(10,15))
print(numbers)
#output
[10, 11, 12, 13, 14]
range() function makes it also available to generate a sequence of number with specified gap. In the following example, we create a list with even numbers between 10 and 20.
#generate a list of even numbers between 10 and 20.
#using the option of gap with 2 in the range() function
e_nr = list(range(10,20,2))
print(e_nr)
#output
[10, 12, 14, 16, 18]
A list can be created with an empty list first. Then the elements of the expected list can be appended to the empty one by one using a for loop. In the following example, we create an empty list using double brackets, then the squares of integers between 10 and 20 are created and added into the list.
#empty list
sqrs = []
#for loop to add element into list one by one
for nr in range(10,20):
sqr = nr**2
sqrs.append(sqr)
print(sqrs)
#output
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
Of course, the temporary variable ‘sqr’ can be omitted for brevity, which is shown in the following example.
#empty list
sqrs = []
#for loop with range() function to create squares of
#integers between 10 and 20
for nr in range(10,20):
sqrs.append(nr**2)
print(sqrs)
#output
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…