Pythonic way to combine (interleave, interlace, intertwine) two lists in an alternating fashion?
python
Solution
Here's one way to do it by slicing:
>>> list1 = ['f', 'o', 'o']
>>> list2 = ['hello', 'world']
>>> result = [None]*(len(list1)+len(list2))
>>> result[::2] = list1
>>> result[1::2] = list2
>>> result
['f', 'hello', 'o', 'world', 'o']
Problem
I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list. ``` # example inputs list1 = ['f', 'o', 'o'] list2 = ['hello', 'world'] # desired output ['f', 'hello', 'o', 'world', 'o'] ``` This works, but isn't pretty: ``` list3 = [] while True: try: list3.append(list1.pop(0)) list3.append(list2.pop(0)) except IndexError: break ``` How else can this be achieved? What's the most Pythonic approach? If you need to handle lists of mismatched length (e.g. the second list is longer, or the first has more than one element more than the second), some solutions here will work while others will require adjustment. For more specific answers, see How to interleave two lists of different length? to leave the excess elements at the end, or How to elegantly interleave two lists of uneven length? to try to intersperse elements evenly, or Insert element in Python list after every nth element for the case where a specific number of elements should come before each "added" element.
Related problems
- Interleave multiple lists of the same length in Python
- How do I make a flat list out of a list of lists?
- Insert element in Python list after every nth element
- How to interleave two lists of different length?
- Pythonic way to mix two lists
- How to elegantly interleave two lists of uneven length?
- Alternating between iterators in Python