We provide effective and economically affordable training courses for R and Python, click here for more details and course registration !

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]

For more tutorials of learning Python, you can watch Python full video in 10 hours from our YouTube channel !


0 Comments

Leave a Reply

Avatar placeholder