0

I have the following list:

users = [
    "user1",
    "user2",
    "user3"
    ]

and I have this for loop, that loops through another list:

for item in ids:
    myfunction(item, user) # ???

I'm not sure how to make this loop. What I want to to is, for each item the loop goes through, it should execute myfunction(item, user), but the user variable should be a user from the users list, and for each item, the user should not be the same (when it gets to the end of the users list, it may come back to user1, and repeat the loop).

It should execute something like this:

myfunction(item, "user1")
myfunction(item, "user2")
myfunction(item, "user3")

How can I achieve something like this?

Thank you

munich
  • 500
  • 1
  • 6
  • 16
  • Duplicate? http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python – tepl Aug 31 '15 at 04:54

5 Answers5

4
for counter, item in enumerate(ids):
    user = users[counter % len(users)]
    myfunction(item, user)
anupsabraham
  • 2,781
  • 2
  • 24
  • 35
1

So you want each item to only execute for 1 user? if so you can do this

for i, item in enumerate(ids):
    myfunction(item, users[i%len(users)])
logee
  • 5,017
  • 1
  • 26
  • 34
0

itertools has a useful function called product() which you can use to generate the cartesian product of arbitrary number of groups of elements without nesting for loops.

import itertools

for (item, user) in itertools.product(ids, users):
    myfunction(item, user)
lemonhead
  • 5,328
  • 1
  • 13
  • 25
  • If you are going to use itertools to avoid multiple loops, you may as well go all the way with map: `map(myfunction, itertools.product(ids, users))` :) – AChampion Aug 31 '15 at 04:53
  • also, reading over the question prompt again looks like the question is asking something different than will be solved by `product` – lemonhead Aug 31 '15 at 04:56
  • Yes, `zip` and `cycle` should do what the OP wants. – AChampion Aug 31 '15 at 05:10
0

Sounds like you want to loop once through ids, and repeat users as many times as is necessary.

from itertools import cycle

for item, user in zip(ids, cycle(users)):
    my_function(item, user)
Cyphase
  • 11,502
  • 2
  • 31
  • 32
  • Wouldn't `cycle` do the same as `chain.from_iterable(repeat(...))`, e.g.: `map(myfunction, zip(ids, itertools.cycle(users)))` – AChampion Aug 31 '15 at 05:08
  • @achampion, I _knew_ I was missing something; I was only half paying attention when I answered that. Thanks :). – Cyphase Aug 31 '15 at 06:10
-2

if you want to forever loop, the follow is what you need:

    user_map = {}
    while True:
        for user in users:
            if user_map.has_key(user):
                continue
            user_map[user] = 1
            for item in ids:
                myfunction(item, user)