Pythonic way to append list of strings to an array

I'm new to Python and come from a Java background. I'd like to know the most Pythonic way of writing this code:

entry_list = [] for entry in feed.entry: entry_list.append(entry.title.text)

Basically for each element in the feed, I'd like to append that element's title to a list.

I don't know if I should use a map() or lambda function or what...


-------------Problems Reply------------

most pythonic code I can think of:

entry_list = [entry.title.text for entry in feed.entry]

This is a list comprehension which will construct a new list out of the elements in feed.entry.title.text.

To append you will need to do:

entry_list.extend([entry.title.text for entry in feed.entry])

As a side note, when doing extend operations, the normally fast generator expression is much slower than a list comprehension.

With a little bit of trickery courtesy of a genex.

entry_list.extend(x.title.text for x in feed.entry)

Or just a LC if you don't need to keep the same list.

entry_list = [x.title.text for x in feed.entry]

Always use List Comprehension for concise expressions.

entry_list = [entry.title.text for entry in feed.entry]

If all that you want to do with the entry_list is to iterate over it again, you can use the generator expression

entry_list = (entry.title.text for entry in feed.entry)

Notice that the only difference is in using parenthesis. When using the generator format, the entry_list is not populated and can save the memory. You will still be able to do things like

for items in entry_list:
do something



Category:python Views:0 Time:2011-11-03
Tags: python

Related post

Copyright (C), All Rights Reserved.

processed in 0.142 (s). 11 q(s)