Ev. Kounis Ev. Kounis - 5 months ago 9
Python Question

List Comprehension - Double Loop or Not?

I am having the following issue:

# Neither this

trial1 = [[x for x in 10000 // 5**i] for i in range(1, 10)]

# nor this

trial2 = [x for i in range(1, 10) for x in 10000 // 5**i]

# work.


They both return: "int" object is not iterable, which is somehow confusing to me. Since
i
is an array
(1,2,3,...,9)
so must be the
10000 // 5**i
formula. So which is the integer
i
can't iterate over?. I want
trial
to be a list containing all these values.

How is this so different?

trial = []
for i in range(1, k):
trial.append(10000 // 5**i)


How does one go about formulating the list comprehension statement?

Answer

The comprehension equivalent of your working for loop would be:

[10000 // 5**i for i in range(1, 10)]

There are no double loops in that example, so there shouldn't be in the comprehension either.

Regarding your second question; i is not a list with values (0, 1, ... , 9) but it is a single integer out of that list.

Comments