Ev. Kounis Ev. Kounis - 1 year ago 65
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
is an array
so must be the
10000 // 5**i
formula. So which is the integer
can't iterate over?. I want
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download