Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
cryptoref Avatar asked Mar 02 '16 16:03

cryptoref


People also ask

Can you use while loops in list comprehension Python?

No, you cannot use while in a list comprehension.

Can we use nested loop in list comprehension?

Example List comprehension nested for loop. Simple example code uses two for loops in list Comprehension and the final result would be a list of lists. we will not include the same numbers in each list. we will filter them using an if condition.


2 Answers

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])
like image 170
midori Avatar answered Oct 17 '22 16:10

midori


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.

like image 33
Tim Pietzcker Avatar answered Oct 17 '22 16:10

Tim Pietzcker