user110
user110

Reputation: 649

Better way of iterating over two lists

I have two lists, say X and Y.

I want to iterate over them, find out the current list I am on and then perform such list-specific operation.

I am doing this:

for e in [x, y]:
    if e == x: doSomethingOnElementsOfX();
    if e == y: doSomethingOnElementsOfY();

Is there a better way? I don't care for speed, just want to know if there is a better syntax for such a case.

Upvotes: 0

Views: 85

Answers (3)

efeder
efeder

Reputation: 562

Python provides a built-in function called zip that should do this for you. zip iterates over an arbitrary number of lists at the same time. This should work as long as the lists are the same length, like so:

for e_in_x, e_in_y in zip(x, y):
    doSomethingOnElementsOfX(e_in_x)
    doSomethingonElementsOfY(e_in_y)

For other more complicated types of list iterations, there's a great python module called itertools with great functions for iterating over collections in different ways.

For example, if the two lists are different lengths, you can do:

for ex, ey in itertools.izip_longest(x, y, fillvalue=None):
    if ex:
        doSomethingOnElementsOfX(ex)
    if ey:
        doSomethingOnElementsOfY(ey)

Upvotes: 0

user2671156
user2671156

Reputation: 33

If you have two lists of the same size you can iterate through both lists in one loop, such as (in Java):

for (int i = 0; i < listSize; i++) {
if e == x: doSomethingOnElementsOfX();
    if e == y: doSomethingOnElementsOfY();
}

otherwise you'd need to do two seperate loops, such as:

for (int i = 0; i < X.listSize; i++) {
    if e == x: doSomethingOnElementsOfX();
}
for (int i = 0; i < Y.listSize; i++) {
    if e == y: doSomethingOnElementsOfY();
}

This is a brute force way of doing it though. If more information was given you can get more appropriate solutions.

Upvotes: 1

Claudiu
Claudiu

Reputation: 229361

The approach I take is to iterate over tuples where the extra element indicates the flag variable, or whatever is different, e.g.:

for (should_chomp, cur) in ((True, x), (False, y)):
    complicated_stuff(cur)
    really_takes_code(cur)
    but_mostly_the_same(cur)
    do_the_different_thing_though(cur, should_chomp)

Upvotes: 0

Related Questions