You are on page 1of 2

Lesson 17- Range function and

List assignments
Range() powerful sequence generator
Range(0,5) 0,1,2,3,4

Range Function in For Loops


Using the range() function
Nums = [10, 20, 30, 40, 50]
Len(nums) = 5
Range( len(nums)) = 0,1,2,3,4
Loop variable iterating over the elements of a sequence
Nums = [10,20,30,40,50,60]
For k in nums:
Sum = sum + k
Loop variable iterating over the index values of a sequence
Nums = [10,20,30,40,50,60]
For k in range(len(nums)):
Sum = sum + nums[k]
Evaluate
For k in range( len(Nums) ):
Print(Nums[k])

Write a for loop to add 1 point to every mark


i.e Change values in list
class_grades = [50,55,54,53,50,56]
for k in range(len(class_grades)):
class_grades[k] = class_grades[k] + 1

To do this, the index value(the location) of each element must be used to update
each grade value

In this case, loop variable k is functioning as an index variable


An index variable is a variable whos changing value

The Range function generates a sequence of consecutive integers,


A step value can be provided:
Range(Start, end, step)
Range(0,11,2) 0,2,4,6,8,10
Range(10,0,-1) 10,9,8,7,6,5,4,3,2,1
Nums = [40,10,60]
For k in range(len(nums)-1,-1,-1):
Print(Nums[k])

Handling Lists
In python, if we assign a variable list:
List2 = List1
Each variable ends up referring to the same instance of the list in memory
List1 = [10,20,30,40,50]
List2 = list1
List1[0] = 5
List1 = [5,20,30,40,50] change made in list1
List2 = [5,20,30,40,50] change in list1 caused
Python is jewish it likes to save memory

You might also like