[Tutor] List comprehension and generators.

Shawhan, Doug (EM, ITS) Doug.Shawhan at ge.com
Thu Apr 8 17:39:47 EDT 2004


Howdy,

Been playing at chopping up strings with list comprehension:

>>> s='hondoharrietshappyhippiehuthyundai'

>>> [(s[:3]) for each in range(5)]
['hon', 'hon', 'hon', 'hon', 'hon']

and more fun..

import random
>>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))]
['hondoharri', 'hondoharri', 'h', 'hond', 'hondoharr', 'hondohar', 'h', 'hondoharri']

>>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))]
['ho', 'ho', 'hondoharri']

>>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))]
['hondoharri', 'hondo', 'hondohar']

>>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))]
['hondoh', 'hondoha', 'hondoha', 'hondoh', 'hondoharri', 'hon', 'hondoharr', 'hondohar']

Now this is all very fun, but it leads me to three questions:

1. How would one split that entire string into a list of same-size elements:

I.e. ['hondoh', 'arriets', 'happyhi', 'ppiehuth', 'yundai']

2. How would one split that string into a list of *non-repeating* random-sized elements?

I.e. ['ho', 'ndoharri', 'etshappyhippieh', 'uthyundai']

(I know I could do it with a 'for' loop, but I'll bet you can do it with list comprehension)

Which in turn leads me to:

3. How would one use comprehension or a generator to create a random-sized list of random numbers? (Or is this not the proper use of a generator?)





More information about the Tutor mailing list