Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - List comprehension how to insert 2 elements at a time?

I have a pluralize function in python which prints the plural form of a word

pluralize("wolf") = wolves

for example, in my input_list

input_list = ["wolf","dog","cat","cow","pig"]

I can do this simple list comprehension to get the plural forms populated

output_list = [pluralize(data) for data in input_list]

giving ["wolves","dogs","cats.....]

However I need

["wolves","wolf","dogs","dog","cats","cat","cows","cow"....]

How can I get this list generated by comprehension?

I mean something like

output_list = [pluralize(data),data for data in input_list]

(obviously doesn't work)

like image 497
wolfgang Avatar asked Dec 06 '25 16:12

wolfgang


2 Answers

sum([[x, plural(x)] for x in data], [])

likewise:

>>> sum([[x, x.upper()] for x in "hello"], [])
['h', 'H', 'e', 'E', 'l', 'L', 'l', 'L', 'o', 'O']
like image 181
tangentstorm Avatar answered Dec 09 '25 04:12

tangentstorm


You could add another loop:

[word for data in input_list for word in (pluralize(data), data)]

Demo:

>>> plural_forms = {'wolf': 'wolves', 'dog': 'dogs', 'cat': 'cats', 'cow': 'cows', 'pig': 'pigs'}
>>> pluralize = plural_forms.get
>>> input_list = ["wolf","dog","cat","cow","pig"]
>>> [word for data in input_list for word in (pluralize(data), data)]
['wolves', 'wolf', 'dogs', 'dog', 'cats', 'cat', 'cows', 'cow', 'pigs', 'pig']
like image 34
Martijn Pieters Avatar answered Dec 09 '25 06:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!