Python Code Example: passing list to method

This code snippet defines a function that doubles each element in a list and then demonstrates its use by doubling the elements of a given list.

Code Example

def doubles(l):
    for i in range(0, len(l)):
        l[i] = 2 * l[i]


myList = [12, 20, 14, 4, 5, 44, 74]

doubles(myList)

print("values from array doubled: ")
for i in range(0, len(myList)):
    print(myList[i], end=' ')

Output

24 40 28 8 10 88 148

Code Explanation

Function doubles(l)

def doubles(l):
    for i in range(0, len(l)):
        l[i] = 2 * l[i]
  • Purpose: This function modifies a list l by doubling each of its elements.
  • Parameter: The function takes one parameter l, which is a list of numbers.
  • For Loop:
    • The loop iterates over each index i of the list from 0 to len(l) - 1.
    • Inside the loop, each element at index i is multiplied by 2 and the result is assigned back to l[i].
  • Effect: The list l is modified in place, meaning the original list passed to the function will be changed.

Main Program

myList = [12, 20, 14, 4, 5, 44, 74]
  • List Initialization: A list myList is created with the values [12, 20, 14, 4, 5, 44, 74].
doubles(myList)
  • Function Call: The doubles function is called with myList as its argument. This will modify myList by doubling each of its elements.
print("values from array doubled: ")
  • Print Statement: This line prints a message indicating that the values from the array have been doubled.
for i in range(0, len(myList)):
    print(myList[i], end=' ')
  • For Loop and Print:
    • This loop iterates over each index i of the list myList from 0 to len(myList) - 1.
    • Inside the loop, each element of myList is printed on the same line separated by spaces. The end=' ' argument in the print function prevents a newline from being added after each print statement, resulting in a single line output.

Example Execution

When the main program is executed, the following steps occur:

  1. The list myList is initialized with the values [12, 20, 14, 4, 5, 44, 74].
  2. The doubles function is called with myList as the argument, which modifies myList to [24, 40, 28, 8, 10, 88, 148].
  3. The modified list is printed with the message “values from array doubled: “.