0

i am trying to combine list1 and list2 in a way that in the end list would look like this ["a", "b" , "c", "d"]

How do i do this?

list1 = ["a", "c"]
list2 = ["b", "d"]
New Dev
  • 44,330
  • 12
  • 76
  • 113
  • `list(itertools.chain.from_iterable(zip(list1, list2)))` – han solo Aug 22 '20 at 17:39
  • 1
    For **fun** `sum(zip(list1, list2), ( ))`. ' : ). You can convert that to `list` if it matters – han solo Aug 22 '20 at 17:41
  • or `[v for pair in zip(list1, list2) for v in pair]`. Hrm, feels like there are many ways. I would consider the first one, or this one for real use. **Also, feels like a duplicate** – han solo Aug 22 '20 at 17:46
  • Does this answer your question? [Pythonic way to combine two lists in an alternating fashion?](https://stackoverflow.com/questions/3678869/pythonic-way-to-combine-two-lists-in-an-alternating-fashion) – Henry Yik Aug 22 '20 at 18:06
  • Did you want it sorted or did you intend to get the first index of each, then the second index of each? – ChipJust Aug 22 '20 at 18:22

5 Answers5

0

You can use the sorted() function python provides in the following way:

    list1 = ["a", "c"]
    list2 = ["b", "d"]
    res = sorted(list1 + list2) 

The + operator will first append the 2 lists together, the result of which is ['a', 'c', 'b', 'd']. It is then passed to the sorted() python function, which will sort the contents of the list in the ascending order as desired i.e. ['a','b','c','d']

schezfaz
  • 329
  • 1
  • 9
0
list1 = ["a", "c"]
list2 = ["b", "d"]

list3 = list1 + list2
list3.sort()

print(list3)
Ktoto
  • 91
  • 6
0

You can do this in many ways, but the main idea is to use zip to merge them,

>>> list1
['a', 'c']
>>> list2
['b', 'd']
>>> import itertools
>>> list(itertools.chain.from_iterable(zip(list1, list2))
... )
['a', 'b', 'c', 'd']
>>> sum(zip(list1, list2), ()) # just for fun
('a', 'b', 'c', 'd')
>>> [v for pair in zip(list1, list2) for v in pair]
['a', 'b', 'c', 'd']
>>>
>>> import functools
>>> functools.reduce(lambda x, y: x+y, zip(list1, list2), ()) # is kinda bad, because it's a bit hard to reason about but fun
('a', 'b', 'c', 'd')
>>> list(itertools.chain(*zip(list1, list2)))
['a', 'b', 'c', 'd']
han solo
  • 5,018
  • 1
  • 7
  • 15
0

you can use extend() and sort() functions;

list1.extend(list2)
list1.sort()
print(list1)

output:

['a', 'b', 'c', 'd']
Juhi Dhameliya
  • 147
  • 2
  • 9
0

Budy you can do this by simply add list1 and list2 and assign result to finallist and then sort final list. Then you can get desired result.

list1=["a","c"]
list2=["b","d"]
finallist=list1+list2
finallist.sort()
print(finallist)

Output:

['a','b','c','d']
Varun
  • 9
  • 1