Reputation: 71
I have two list of different lenghts.
list_a = ['pineapple', 'banana', 'mango']
list_b = ['tropical']
I want to combine them as follows:
final_list = ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']
the goal is to get a dataframe in the end that includes the variable "fruits" and the variable "origin". I will do that by creating a list that displays only every second element and combine then afterwards.
What I already tried:
fruit_origin = list_b[0]
desired_list = list(map(fruit_origin.__add__, list_a))
but this returns it like this:
['pineappletropical', 'bananatropical', 'mangotropical']
thanks in advance!
Upvotes: 0
Views: 76
Reputation: 778
I think a nested loop is more readable in this case than a one liner
list_a = ['pineapple', 'banana', 'mango']
list_b = ['tropical']
final_list = []
for a in list_a:
final_list.append(a)
for b in list_b:
final_list.append(b)
Upvotes: 1
Reputation: 18416
You can multiply second list by number of items in the first list, and use zip
and comprehension like this:
[item for x in zip(list_a, list_b*len(list_a)) for item in x]
Out[7]: ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']
Upvotes: 1
Reputation: 73460
You can use zip
, itertools.cycle
, and a nested comprehension à la:
from itertools import cycle
list_a = ['pineapple', 'banana', 'mango']
list_b = ['tropical']
[x for tpl in zip(list_a, cycle(list_b)) for x in tpl]
# ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']
You can also use itertools.chain
to flatten the pairs, as suggested by @Matthias:
from itertools import cycle, chain
[*chain(*zip(list_a, cycle(list_b)))] # Python >= 3.5
# or more verbose
list(chain.from_iterable(zip(list_a, cycle(list_b))))
Upvotes: 3
Reputation: 54148
Combine itertools.cycle
, zip
and itertools.chain
cycle(['tropical'])
=> 'tropical', 'tropical', 'tropical', 'tropical', ...
zip(['pineapple', 'banana', 'mango'], ['tropical', 'tropical', 'tropical'])
=> [('pineapple', 'tropical'), ('banana', 'tropical'), ('mango', 'tropical')]
list(chain(*[('pineapple', 'tropical'), ('banana', 'tropical'), ('mango', 'tropical')]))
=> ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']
Final code
result = list(chain(*zip(list_a, cycle(list_b))))
Upvotes: 1
Reputation: 2061
I'm not sure if I understood your question correctly, but if you want to map the origin which I'm assuming is only the 1 element in the list. You can try this:
desired_list = []
for fruit in list_a:
desired_list.append(fruit)
desired_list.append(list_b[0])
print(desired_list)
Output:
['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']
Upvotes: 1