0

How can I replace each element of list with a new number that is equal to the product of itself and a number that I provide using a function. I am performing the desired goal by defining new list D.

D=[]
S= [1,2,3,4]

def num(x):
    for i in S:
        D.append(i*x)
    return D

num(2)

In the above example, the output for D is [2, 4, 6, 8], and S remains unchanged. I would rather want S to change to [2, 4, 6, 8]

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
Shah5105
  • 57
  • 2
  • 8
  • 2
    why do you need to replace elements in original `list`? also mutating objects from outer scope may lead to undesired behavior in the long run – Azat Ibrakov Nov 29 '18 at 19:58

3 Answers3

0

Instead of appending the value to a new list, you can overwrite the existing value as follows:

S = [1,2,3,4]

def num(x):
    for i in range(0, len(S)):
        s[i] *= x
Omari Celestine
  • 1,405
  • 1
  • 11
  • 21
0

You have many options to do it. Either you directly manipulate S or you reassign it:

def num(x):
    global S
    for index, value in enumerate(S):
        S[index] = value * x

def num(x)
    inner = []
    for i in S:
        inner.append(i*x)
    return inner
S = num(2)

And a more sane version:

S = [i*2 for i in S]

Now the important part, why is this sane? Well since lists in python are not immutable you have to be careful how you go about changing them. In your case making a function which relies on the value of a variable outside of the function is risky. If you always want the first list and you change(mutate) it inside a function you will end up with problems. If you really want to mutate your original list then it's fine, but still you achieve the same thing with list comprehension (the last option listed).

Borisu
  • 828
  • 7
  • 15
0

You should probably take the list into the function as well. Then mutate it's elements and (optionally) return it ast well:

def num(data,multi):
    """Multiplies each element of data (a list of ints) by multi.
    The original list is modified and returned as well for chaining."""
    # data[:] = [d*multi for d in data]  # inplace reassignment list comp
    # or
    for i,d in enumerate(data[:]): # this iterates a _copy_ of data, do not modify a list
        data[i]=d*multi            # that you currently iterate over - it is possible here
                                   # but often it is a bad idea if you add/remove things
    return data

S= [1,2,3,4]
num(S,2)

print(S)

Output:

[2,4,6,8]

There are several dupes out on SO:

Some of them for python2 where map still returns a list - you can look them up for even more options.

Returning the list inside the function as well, will allow you to chain calls:

num(num(num(S,2),3),4) # S = [24, 48, 72, 96]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69