[Tutor] interesting str behavior ...

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri May 16 02:24:03 2003


On Thu, 15 May 2003, David Broadwell wrote:

> This will be trivial for most but;
>
> I have known strings are iterable for awhile ... However, the code below
> struck it home. Now I believe they are.
>
> >>> from string import letters
> >>> temp = []
> >>> temp.extend(letters)
> >>> temp
> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
> 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
> 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
> 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']


Hi David,

Another neat way to get a similar effect is to 'list' an iterable thing.
For example:

###
>>> list("hello world")
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>>
>>> d = {1:'one', 2:'two', 3:'three'}
>>> list(d)
[1, 2, 3]
###

The second example is slightly obscure but cute: dictionaries are
iterable: we can march through their keys,

###
>>> for key in d:
...     print "here's a key", key
...
here's a key 1
here's a key 2
here's a key 3
###

and that explains the slightly odd-looking result of list()ing a
dictionary.


> Ah learning from mistakes ...

Fastest way to learn anything, and, most of the time, pretty painless.
*grin*



> I was testing something in the interpreter, and grabbed a string not a
> list to look at list.extend().
>
> The closest I can code to 'extend' is;
> >>> temp = []
> >>> temp.append([item for item in letters])
> >>> temp
> [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
> 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
> 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
> 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']]
>
> Though that isn't perfect ... it is much the same semantics.

It's also good to see that what we get here makes its own sort of sense.
When we append() anything to a list, we make the list grow by one element,
no matter what we put into the list.  So the length of the 'temp' is one:

###
>>> len(temp)
1
###


If we want to make temp 56 elements long, and if we want to do it by using
append() only, we've got to do something to let us do a repeated append()
that many times.


Good luck to you!