Sunday, September 19, 2021

Passing an entire List to a Function

We are going to pass an entire list to a function.

    In [1]: numbers
    Out[1]: [10, 5, 3, 7, 4]

Defining a function which we going to pass the entire list to.  This function multiplies each of the list's element by 2.
    In [2]: def modify_elements(items):
    ...:     for i in range(len(items)):
    ...:         items[i] *= 2
    ...:

    In [3]: modify_elements(numbers)

    In [4]: numbers
    Out[4]: [20, 10, 6, 14, 8]

    In [5]:

Function modify_elemens' items parameter receives a reference to the original list, so the statement in the loop's suite modifies each element in the original list object.

No comments:

Post a Comment