Confused by List behavior

Gordon McMillan gmcm at hypernet.com
Thu Apr 20 14:14:18 CEST 2000


ejbaker_seekonk at my-deja.com wrote:

> As a python newbie, I entered this script to explore list processing
> behaviours.
> 
> yy = dir()
> for element in yy:
>   print element
> 
> for element in yy:
>   print dir(element)
> 
> The first 'for' loop works as expected. It returns,
> ['__builtins__', '__doc__', '__name__'].
> 
> The second loop, however, returns three empty lists. For the life of
> me, I can't understand that. Becauese, if I type 'dir(__builtins__)',
> in a script, I get all of the elements of __builtins__.

You're confused by dictionaries, not lists. dir() returns the 
names of the objects (that is, a list of strings), not the objects 
themselves. 

One way:
  for element in dir():
    print dir(eval(element))

More sensibly:
  for key, val in vars().items():
    print key, val, dir(val)

- Gordon




More information about the Python-list mailing list