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.
No, you cannot use while in a 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.
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])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With