4

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...

Thanks

3
  • @pst that's no help at all. i know how to write the code multiple ways, i'm asking for other people's advice for the best way to do it. Commented Nov 5, 2011 at 15:27
  • I could swear it covers all the methods below -- list comprehensions in particular ;-) Commented Nov 5, 2011 at 18:05
  • Right, it has a multitude of ways to approach the problem, including the one I took... I need advice for which one to choose. Commented Nov 7, 2011 at 19:16

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

List comprehension. The list constructor is list().
4

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]

3 Comments

for some reason, list comprehensions are faster than generator sequences for the extend functionality.
Makes sense. With a LC it can just reallocate the list all in one go, whereas with a genex it has to reallocate for each yielded value or so.
Thanks, I forgot about list comprehension
3

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

and

''.join(entry_list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.