[Tutor] List comprehension and generators.

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Apr 9 13:42:47 EDT 2004



On Thu, 8 Apr 2004, Shawhan, Doug (EM, ITS) wrote:

> 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']


Hi Doug,


It's possible to do this with the list comprehension approach that you're
using now.  The range() builtin can take in 3 arguments: a 'start', an
'end' and a 'skip':

###
>>> range(0, 10, 3)
[0, 3, 6, 9]
###


We can combine this with list slicing to dice up a list:

###
>>> numbers = range(50)
>>> [numbers[i:i+5] for i in range(0, 50, 5)]
[[0, 1, 2, 3, 4],
 [5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14],
 [15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24],
 [25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34],
 [35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44],
 [45, 46, 47, 48, 49]]
###



There are other approaches we can take.  In particular, we can even use
regular expressions:

###
>>> re.findall('.....', "supercalifragilisticexpialidosious")
['super', 'calif', 'ragil', 'istic', 'expia', 'lidos']
###

This may be easier to comprehend than comprehensions, depending on your
background.




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

Can you write a function that takes that string and returns a list of
random-sized elements?  And is there a specific number of chunks that we
want to break our string into?  Do we always want to break the string into
5 or 6 parts, or is that too meant to be random?

It may be easier to approach the more-general problem, and then tack on
the requirement for 'non-repeats' as a refinement afterwards.





> 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?)

This feels like list comprehension abuse to me.  Any implemenation that
makes this work will probably be nonobvious.  *grin*

Is there a specific requirement to use comprehensions?  Using loops might
be more straightforward.


Talk to you later!





More information about the Tutor mailing list