Tawsif Haque
Tawsif Haque

Reputation: 41

I want to pass a list to a function, and expect the function to modify the list

The code for modifying a list passed as argument is as follows. The code does not work. I want to know why it doesn't.

def modify_list(some_list):
    for item in some_list:
        item *= 2
        some_list.append(item)
    return some_list

modify_list([2, 4, 6])

Upvotes: 0

Views: 78

Answers (2)

mozway
mozway

Reputation: 260420

In case you want the function to actually modify the list in place:

def modify_list(some_list):
    for i, item in enumerate(some_list):
        some_list[i] *= 2
    

l = [2,4,6]
modify_list(l)

Output:

>>> l
[4, 8, 12]

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191701

You cannot append to a list while iterating because then the loop will never end. If you want to append new elements from the existing list, then extend the input with those values

def modify_list(some_list):
  new_elements = [i*2 for i in some_list]
  some_list.extend(new_elements)
  return some_list

Keep in mind, that functions should not have "side-effects"; don't modify the input object reference, which you can do like this

def modify_list(some_list):
  copy = some_list[:]
  new_elements = [i*2 for i in some_list]
  copy.extend(new_elements)
  return copy

If you want to multiply each element by two, then you don't need a function for that

some_list = [2, 4, 6]
some_list = list(map(lambda x: 2*x, some_list))

Upvotes: 2

Related Questions