cryptoref
cryptoref

Reputation: 413

list comprehension with concurrent loops python

Simple question as i just want to write more pythonic code. I want to convert the following into a list comprehension

index_row = 0
for row in stake_year.iterrows():
    self.assertTrue(row[0] == counts[index_row][0])
    self.assertTrue(row[1][0] == counts[index_row][1])
    index_row += 1

What i don't understand is how to walk through the counts list. I don't want a nested for like:

[self.assertTrue(x[0] == counts[y][0] for x in stake_year for y in counts]

The code i have now is working but I'd like to understand python better and use the language as it should be used.

Upvotes: 5

Views: 451

Answers (2)

midori
midori

Reputation: 4837

The more pythonic way to use in your case is to use enumerate:

for index_row, row in enumerate(stake_year.iterrows()):
    self.assertTrue(row[0] == counts[index_row][0])
    self.assertTrue(row[1][0] == counts[index_row][1])

Upvotes: 7

Tim Pietzcker
Tim Pietzcker

Reputation: 336428

Don't.

List comprehensions are not by definition more pythonic than simple loops - only if these loops are designed to build new lists (or dicts, sets etc.), and if the listcomp is easier to read than the loop.

This is not the case in your example (you're not building anything), and you shouldn't use a listcomp only for its side effects, that would be patently unpythonic.

So it's good to convert

result = []
for line in lines:
    result.append(line.upper())

into

result = [line.upper() for line in lines]

but not your example.

Upvotes: 5

Related Questions