Tohiko
Tohiko

Reputation: 1982

Pythonic way to construct a list

Is there a Pythonic way to to construct the following list (or similar):

N = 32000

my_list = []
l = 0 
while N // 2**l % 2 == 0:
     my_list.append(N // 2**l)
     l += 1

As far as I can see there's no way to break from the usual list construction syntax, [i for i in range(10)], nor a way to specify an open-ended for-loop.

Upvotes: 0

Views: 270

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45740

You could split this into two parts: the production of the calculations, and the handling of the end condition.

Producing an infinite sequence of calculations is straightforward:

from itertools import count, takewhile

N = 32000

nums = (N // 2**l for l in count())

Where count is like range, but no end is specified.

To cut it off, you can pair that with takewhile, and negate the condition:

finite_nums = takewhile(lambda n: n % 2 == 0, nums)

>>> list(finite_nums)
[32000, 16000, 8000, 4000, 2000, 1000, 500, 250]

Upvotes: 4

Youyoun
Youyoun

Reputation: 338

Besides looking into what pythonic may mean to you, because I think that each of us has his own opinion of what pythonic is, you could simply rewrite your loop like so:

while not N // 2**l % 2 != 0:
     my_list.append(N // 2**l)
     l += 1

Or did you mean rewrite your list as a comprehension ?

Upvotes: 0

Related Questions