[Tutor] implementing a table data structure in python?

Kent Johnson kent37 at tds.net
Tue Dec 21 16:12:28 CET 2004


Maarten wrote:
> So maybe a bit bold for a newbie to start posting a correction but i 
> wanted the code to work:
> 
> Kent Johnson wrote:
> <snip>
> 
>> columns = [1,3,4]  # Column numbers to show, 0-based
>>
>> f = open('mydata.txt')
>> for line in f:
>>     data = line.split()  # Assuming your data is tab- or space-delimited
>>     data = [ item for i, item in data if i in columns ]  # Filter out 
>> unwanted columns
>>     print data  # Output one row of text - put your formatting here
> 
> guess Kent forgot one line after:
> 
>     data = line.split()
> 
> adding next line after it:
> 
>     data = enumerate(data)
> 
> makes it work for me.

Ah, right you are. I should know better than to post code without trying it! Actually I meant to write
   data = [ item for i, item in enumerate(data) if i in columns ]
which is just a more compact way of saying the same thing.

> Still got a question. This notation/syntax of the list:
> 
> [ item for i, item in data if i in columns ]
> 
> is quite new for me. Can someone point me to more examples of this use 
> Or give me the name of it (it must have a name) so i can google it?

It's called a 'list comprehension'. It is a handy shortcut for a loop that builds a list from 
another list. You can read more about them here:
http://docs.python.org/tut/node7.html#SECTION007140000000000000000

The line
   data = [ item for i, item in enumerate(data) if i in columns ]

is equivalent to
temp = []
for i, item in enumerate(data):
   if i in columns:
     temp.append(item)
data = temp

List comprehensions are generally more concise, easier to read (once you understand the syntax) and 
faster running than the equivalent spelled-out loop.

Kent


More information about the Tutor mailing list