Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to append list of strings to an array

Tags:

python

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

like image 921
Cuga Avatar asked Dec 07 '22 18:12

Cuga


1 Answers

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.

like image 100
Serdalis Avatar answered Jan 02 '23 15:01

Serdalis