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"]
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"]
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']
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']
you can use extend()
and sort()
functions;
list1.extend(list2)
list1.sort()
print(list1)
output:
['a', 'b', 'c', 'd']
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']