If you ever have multiple lists in Python that you want to combine in one list, don’t panic. Python actually makes it really easy to perform a function like this. You can combine and concatenate lists just by using the plus (+) symbol — seriously, it doesn’t get much easier than that. If you want to get a better idea for how merging lists works, check out the example below.
Let’s say we have two lists, and they’re defined as such:
listone = [9, 13, 16] listtwo = [21, 36, 54]
- Using Python to Check for Number in List | Python List Contains | How to check if element exists in List in Python?
- Python Tricks: Storing Multiple Values | Learn How to Store Multiple Values in Python
- HTML Parser: How to scrape HTML content | Parsing HTML in Python with BeautifulSoup
And now let’s say we want to merge the lists together to create one list. Here’s how that can be done:
newlist = listone + listtwo print newlist
The output of the code above would be: 9, 13, 16, 21, 36, 54. And the new list, of course, would be defined like this: newlist = [9, 13, 16, 21, 36, 54]. It’s that easy to combine two lists to create a new one.