Printing out a list item using a function, for loop, and range


#1

can someone please break down what is happening in this code. I am

familiar with functions, list, for loops, and range, but not when they are

#combined like this. Thank You

n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print (x[i])
print_list(n)

on the console, It printed
3
5
7


#2
def print_list(x):
    for i in range(0, len(x)):
        print (x[i])

n = [3, 5, 7]

print_list(n)

We have a function, print_list which does what its name suggests… print the list that is handed in. Technically, any iterable may be passed it.

[]  =>  list
""  =>  string
''  =>  string
()  =>  tuple
{}  =>  set

The for loop iterates over a range, which values represent the index for each iteration.

m = len(x)

range(m)    =>  [0, 1, 2]

Recall that range excludes the upper bound so,

range(len(x)) will exclude 3 from the list (len(x) is 3).

The print statement outputs the item in the list at index i.

Note that n is a global object which is passed to the function for output.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.