Categories
Python Answers

How to combine two lists in an alternating fashion with Python?

Spread the love

Sometimes, we want to combine two lists in an alternating fashion with Python

In this article, we’ll look at how to combine two lists in an alternating fashion with Python.

How to combine two lists in an alternating fashion with Python?

To combine two lists in an alternating fashion with Python, we can use the slice syntax.

For instance, we write

list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
result = [None] * (len(list1) + len(list2))
result[::2] = list1
result[1::2] = list2

to create the result list that has the length of list1 and list2 combined with

result = [None] * (len(list1) + len(list2))

Then we use

result[::2] = list1

to put the items in list1 in the even indexes of result.

And we use

result[1::2] = list2

to put the items in list1 in the odd indexes of result.

Conclusion

To combine two lists in an alternating fashion with Python, we can use the slice syntax.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *