4

Possible Duplicate:
Python: For each list element apply a function across the list

for example, let's say I have an array or list

myList = [a,b,c,d]

and I have a function that generates a random number.

How do I go through the list and have each of the item in that list receives the random number generated by the function and be added to the item?

So, say 'a' is the 1st in the list, 'a' goes into the function where a random number (let's say 5), is generated and adds itself to 'a' the result should be `[a+5, b+.......].

Community
  • 1
  • 1

4 Answers4

4

You use a list comprehension:

[func(elem) for elem in lst]

For your specific example, you can use an expression that sums the values:

[elem + func() for elem in myList]

where func() returns your random number.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Use map() function, that apply function to every item of iterable and return a list of the results:

def myfunc(x):
     return x ** 2

>>> map(func, [1,2,3])
[1, 4, 9]
defuz
  • 26,721
  • 10
  • 38
  • 60
0

I assume you're talking about integers. This little script should do what you want:

import random

def gen_rand(number):
    generated = random.randint(1, 10) # you can specify whatever range you want
    print generated
    return number + generated

myList = [1,2,3,4,5]
print str(myList)
myList = [gen_rand(item) for item in myList]
print str(myList)

Or you could use the map function instead of the for loop. Replace

myList = [gen_rand(item) for item in myList]

with

myList = map(gen_rand,myList)
Catalin Luta
  • 711
  • 4
  • 8
0

If you need one liner :-)

myList = [1,2,3,4]    
[ i + map(lambda i: random.randint(10,20), myList)[index] for index, i in enumerate(myList) ]
SRC
  • 590
  • 6
  • 22