How to concatenate lists in python

How to concatenate lists in python

How to Concatenate Lists in Python – Detailed Guide

Python Lists are used to multiple items in one variable. Lists are changeable, ordered and it also allows duplicate values. The values are enclosed in square brackets.

You can concatenate Lists to one single list in Python using the + operator.

In this tutorial, you’ll learn the different methods available to concatenate lists in python and how the different methods can be used in different use-cases appropriately.

If You’re in Hurry…

You can use the below code snippet to concatenate two lists in Python.

Snippet

+ operator concatenates the two lists and creates a new list object as a resultant object.

Output

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to join multiple lists to one list object.

Table of Contents

Using + Operator

You can join two or multiple list objects into one list object using the + operator.

Plus operator is normally used to sum the two operands used in it. In the context of a list, it acts as a concatenation operator where it adds the items of the two lists and produces one resultant list object.

Use-case: You can use this method when you want to create a new list object rather than adding the items of one list into the existing list. This is also the fastest method for concatenating lists.

Snippet

This is how you can use the + operator to concatenate two lists and create a new resultant object.

Using Extend()

You can use the extend() method to extend an existing list with one or more additional items. It increases the length of the list by the number of elements passed to the method.

For example, if you pass 5 elements to the extend() method, then it’ll add those 5 elements to the existing list.

Use-Case: You can use this method if you want to add more than one element to an existing list at one shot.

Snippet

You can see all the items on the list even_numbers is added to the existing list odd_numbers at one shot using the odd_numbers.extend(even_numbers) statement.

Output

This is how you can concatenate two lists using the extend() method.

Using Append()

You can use the append() method to add one element at a time to an existing list. It increases the length of the existing list by one at a time.

You cannot add more than one item at once using the append() method.

This doesn’t create a new resultant object. It only appends items to the existing list object.

Use-Case: You can use this method if you want to add only one element to an existing list.

Snippet

You can see that all the items in the even_numbers list are added to the list odd_numbers using the append() method one by one.

Output

This is how you can concatenate two lists using the append() method.

Using * Operator

* operator is python unpacks the items in the collections into a positional argument. This is introduced in the version 3.6.

You can check the python version using the below script.

Script

Output

When you use the * operator in a list, it unpacks the elements in the list so that you can use the items directly. You need not iterate over the list again to access the item.

You can concatenate multiple lists into one list by using the * operator.

For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object.

Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.

Snippet

Output

This is how you can concatenate multiple list objects into one single list object using the * operator.

Using List Comprehension

List comprehension provides a short syntax to create a new list based on the values in the existing list. You can also use list comprehension to concatenate two lists into one single list object.

You need to use two for loops in list comprehension to concatenate two lists into one.

Example: y for x in [odd_numbers, even_numbers] for y in x
where,

Use the below snippet to concatenate two lists into a single list using the list comprehension.

Snippet

Output

This is how you can concatenate lists in python using list comprehension.

Using Itertools.chain()

itertools.chain() chains the iterable arguments into one single iterable object.

A list is an iterable object. Hence, when you pass two lists into the chain() method, it’ll chain the two iterable lists into once.

You need to import the itertools package using the statement import itertools statement.

Usecase: You can use this method when you want to iterate the concatenated list only once and do not want to store the concatenate list for future use.

In the below example, for demonstration purposes, a new list is created out of the chained list returned by itertools.chain() method by passing it to the list() method.

Snippet

You can see the two lists are concatenated into one list called numbers.

Output

This is how you can concatenate multiple lists using the itertools.chain() method when you want to use the concatenated list only once.

These are the different methods available to concatenate lists in python.

Now, you’ll learn how these different methods can be applied in various use-cases.

Concatenate List of Lists

Lists of lists in python is where a list item consists of another list. You can concatenate such a list of lists using the itertools.chain.fromiterable() method.

Use the below snippet to concatenate the list of lists into one single object.

Snippet

Output

This is how you can concatenate a list of lists in python using the itertools() method.

Merge Lists Only Unique Items

You can merge two lists into one single list with only unique items in it. This method can be used when you want to create a single list with unique items and removing the duplicates.

You can use the set() method because python set() is used to create a list of items with unique objects. It doesn’t allow duplicates.

Hence when you pass a list to a set, it removes the duplicates automatically.

Concatenate two lists using the + operator and pass the resultant list to the set() method to remove duplicates. Then to create a list with unique items, you can pass the set to the list() method.

Use the below snippet to merge lists only with unique items. Both the source list contains 0 in it. Hence this needs to be removed while merging two lists.

Snippet

You can see the duplicate element 0 is available only once in the resultant list.

Output

This is how you can join the list only with the unique elements.

Concatenate Two Lists Side By Side

During the normal concatenation operation, all the items in the second list are appended to the items in the first list, and so on. Hence the order of the elements in each list appears the same.

At times, you may need to concatenate items from each list side by side or element-wise.

For Example, you need to add the first elements of the list first, then the second element of the list to be added, then the third element of the list is added, and so on.

You can do this by using the list comprehension and zip() function.

Zip() function is used to create an iterator of tuples with the first item of each iterator is paired together, then the second item of the iterator is paired together, then the third item, and so on.

Then you can use the join() method to join together all the paired tuples to one single list.

Use the below snippet to concatenate two lists side by side to create an order of numbers.

Snippet

You can see the list created with the odd numbers and even numbers merged in order.

Output

This is how you can concatenate two lists side by side or element-wise.

Combine Lists into Dataframe

You can combine more than one list into a dataframe using the pd.Dataframe() method.

Use the zip() method to create a row with one element from each list.

Then create a list of objects with rows using the list() method.

Use the below snippet to combine two or more lists into a dataframe.

Snippet

Dataframe Will Look Like

List 1List 2List 3
0000
1111
2222
3333
4444
5555
6666
7777
8888
9999

This is how you can combine two or more lists into a dataframe using the pd.dataframe() and zip() method.

Conclusion

To summarize, you’ve learned the different methods available to concatenate lists in python. Also, you’ve learned when to use the different methods based on the different use cases such as

Python concatenate list with examples

In this python tutorial, we will discuss the Python concatenate list, and also we will cover these below topics:

Python concatenate list

Here, we can see how to concatenate list in python.

We can see that the two lists are appened as the output. The below screenshot shows the output.

Python concatenate list elements with delimiter

Here, we can see how to concatenate list elements with delimiter in python?

The below screenshot shows the concatenated list with delimiter in python as the output.

Python concatenates a list of lists

Now, we can see how to concatenate a list of lists in python.

Here, we can see that concatenated list of lists is the output. You can refer to the below screenshot for the output.

How to concatenate lists in python. Смотреть фото How to concatenate lists in python. Смотреть картинку How to concatenate lists in python. Картинка про How to concatenate lists in python. Фото How to concatenate lists in pythonPython concatenates a list of lists

This is how to concatenates a list of lists in Python.

Python concatenate a list of integers into a string

Now, we can see how to concatenate a list of integers into a string in python.

The below screenshot shows the output of concatenated string with the delimiter. You can refer to the below screenshot for the output.

This is how to concatenate a list of integers into a string in Python.

Python concatenate a list of tuples

Here, we can see how to concatenate a list of tuples in python

We can see the concatenated tuples as the output. The below screenshot for the output.

This is how we can concatenate a list of tuples in Python.

Python concatenate a list of NumPy arrays

Here, we can see how to concatenate a list of Numpy arrays in python (NumPy in Python)

We can see the concatenated list as the output. You can refer to the below screenshot.

This is how to concatenate a list of NumPy arrays in Python.

Python concatenate a list of strings with a separator

Here, we can see how to concatenate a list of strings with a separator in python

We can see the concatenated list with separator as the output. The below screenshot shows the output.

This is how to concatenate a list of strings with a separator in Python.

Python concatenate a list of dictionaries

Here, we can see how to concatenate a list of dictionaries in python

We can see that the key-value pair of the dictionary is concatenated as the output. You can refer to the below screenshot for the output.

This is how we can concatenate a list of dictionaries in Python.

Python concatenate a list of bytes

Now, we can see how to concatenate a list of bytes in python.

The bytestring is concatenate as the output. The below screenshot shows the output.

This is how to concatenate a list of bytes in Python.

Python concatenate list to string

Now, we can see how to concatenate list to string in python.

The below screenshot show the string is concatenated with separator as the output. You can refer to the below screenshot for the output.

In this way, we can concatenate list to string in Python.

Python concatenates a list of arrays

Here, we can see how to concatenates a list of arrays in python.

We can see the concatenated list of array as the output. You can refer to the below screenshot for the output.

This is how to concatenates a list of arrays in Python.

Python concatenate a list of integers

Now, we can see how to concatenate a list of integers in python

We can see the list of integers are concatenated as the output. You can refer to the below screenshot for the output.

Python concatenate lists without duplicates

Here, we can see how to concatenate lists without duplicates in python

We can see that the list is concatenated without duplicates as the output. You can refer to the below screenshot.

This is how to concatenate lists without duplicates in Python.

Python join list of objects to string

Here, we can see how to join list of objects to string in python

The below screeen shot shows the output.

This is how to join list of objects to string in Python.

Python concatenate multiple lists

Now, we can see how to concatenate multiple lists in python

The below screenshot shows the output.

In this way, we can concatenate multiple lists in Python.

Merge lists python unique

Here we can see how to merge lists unique in python

The below screenshot shows the output.

You may like the following Python tutorials:

In this tutorial, we have learned about Python concatenate list, and also we have covered these topics:

How to concatenate lists in python. Смотреть фото How to concatenate lists in python. Смотреть картинку How to concatenate lists in python. Картинка про How to concatenate lists in python. Фото How to concatenate lists in python

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

How to concatenate lists in python

Python Concatenate Lists

5 minute read Updated: July 6, 2021

How to concatenate lists in python. Смотреть фото How to concatenate lists in python. Смотреть картинку How to concatenate lists in python. Картинка про How to concatenate lists in python. Фото How to concatenate lists in python

Concatenate Two Lists in Python

Problem: You have two lists and you’d like to join them into a new list. Solution:

📢 TLDR: Use +

In almost all simple situations, using list1 + list2 is the way you want to concatenate lists.

Combine Lists In Place In Python

Problem: You have a huge list, and you want to add a smaller list on the end while minimizing memory usage.

In this case, it may be best to append to the existing list, reusing it instead of recreating a new list.

As with any optimization, you should verify that this reduces memory thrash in your specific case and stick to the simple idiomatic x + y otherwise.

Let’s use the timeit module to check some performance numbers.

In this example, where x is 3000 elements, extend is around 50x faster.

❗ Concatenating Lists With Huge Elements is Fine

If the elements in your list are huge (million character strings), but the list size is less than a thousand elements, the previous solution x + y will work just fine. This is because Python stores references to the values in the list, not the values themselves. Thus, the element size makes no difference to the runtime complexity.

In this case, extend does not have an advantage.

Avoid Chain From itertools For Two Lists

It is possible to use chain from itertools to create an iterable of two lists.

We can check the performance of using chain:

Using chain with two lists is slower in all cases tested, and x + y is easier to understand.

Combining N Lists in Python

If you need to add three or even ten lists together and the lists are statically known, then + for concatenate works great.

Flatten a List of Lists in Python

However, if the number of lists is dynamic and unknown until runtime, chain from itertools becomes a great option. Chain takes a list of lists and flattens it into a single list.

chain can take anything iterable, making it an excellent choice for combining lists, dictionaries, and other iterable structures.

Performance of Flattening a List of Lists

Performance doesn’t always matter, but readability always does, and the chain method is a straightforward way to combine lists of lists. That said, let’s put readability aside for a moment and try to find the fastest way to flatten lists.

One option is iterating ourselves:

Let’s check its performance vs chain:

This shows that chain.from_iterable is faster than extend.

Flattening and Merging Lists With One Big List

What about adding a list of lists to an existing and large list? We saw that using extend can be faster with two lists when one is significantly longer than the other so let’s test the performance of extend with N lists.

We then test its performance:

Next, let’s try concatenating by adding everything onto the long list:

There we go, extend is much faster when flattening lists or concatenating many lists with one long list. If you encounter this, using extend to add the smaller lists to the long list can decrease the work that has to be done and increase performance.

Summary

These are the main variants of combining lists in python. Use this table to guide you in the future.

Also, if you are looking for a nice way to standardize the processes around your python projects – running tests, installing dependencies, and linting code – take a look at Earthly for Repeatable Builds.

ConditionSolutionPerformance Optimization 2
2 listsx + yNo
1 large list, 1 small listx.extend(y)Yes
Known number of N listsx + y + zNo
Unknown number of N listslist(chain.from_iterable(l))No
List of Listslist(chain.from_iterable(l))No
1 large list, many small listsfor l1 in l: x.extend(. )Yes

    I did all the performance testing using Python 3.9.5 on MacOS BigSur.↩︎

    If you don’t have a performance bottleneck, clarity trumps performance, and you should ignore the performance suggestions.

    How to concatenate lists in python. Смотреть фото How to concatenate lists in python. Смотреть картинку How to concatenate lists in python. Картинка про How to concatenate lists in python. Фото How to concatenate lists in python

    Spreading the word about Earthly. Host of CoRecursive podcast. Physical Embodiment of Cunningham’s Law.

    How to Concatenate Lists in Python? [Interactive Guide]

    So you have two or more lists and you want to glue them together. This is called list concatenation. How can you do that?

    These are six ways of concatenating lists:

    What’s the best way to concatenate two lists?

    If you’re busy, you may want to know the best answer immediately. Here it is:

    You’ll find all of those six ways to concatenate lists in practical code projects so it’s important that you know them very well. Let’s dive into each of them and discuss the pros and cons.

    Related articles:

    Table of Contents

    1. List Concatenation with + Operator

    If you use the + operator on two integers, you’ll get the sum of those integers. But if you use the + operator on two lists, you’ll get a new list that is the concatenation of those lists.

    The problem with the + operator for list concatenation is that it creates a new list for each list concatenation operation. This can be very inefficient if you use the + operator multiple times in a loop.

    Performance:

    How fast is the + operator really? Here’s a common scenario how people use it to add new elements to a list in a loop. This is very inefficient:

    The experiments were performed on my notebook with an Intel(R) Core(TM) i7-8565U 1.8GHz processor (with Turbo Boost up to 4.6 GHz) and 8 GB of RAM.

    I measured the start and stop timestamps to calculate the total elapsed time for adding 100,000 elements to a list.

    The result shows that it takes 14 seconds to perform this operation.

    This seems slow (it is!). So let’s investigate some other methods to concatenate and their performance:

    2. List Concatenation with append()

    It seems a bit odd to concatenate two lists by iterating over each element in one list. You’ll learn about an alternative in the next section but let’s first check the performance!

    Performance:

    I performed a similar experiment as before.

    I measured the start and stop timestamps to calculate the total elapsed time for adding 100,000 elements to a list.

    The result shows that it takes only 0.006 seconds to perform this operation. This is a more than 2,000X improvement compared to the 14 seconds when using the + operator for the same problem.

    While this is readable and performant, let’s investigate some other methods to concatenate lists.

    3. List Concatenation with extend()

    You’ve studied the append() method in the previous paragraphs. A major problem with it is that if you want to concatenate two lists, you have to iterate over all elements of the lists and append them one by one. This is complicated and there surely must be a better way. Is there?

    You bet there is!

    The difference between append() and extend() is that the former adds only one element and the latter adds a collection of elements to the list.

    The code shows that the extend() method is more readable and concise than iteratively calling the append() method as done before.

    But is it also fast? Let’s check the performance!

    Performance:

    I performed a similar experiment as before for the append() method.

    I measured the start and stop timestamps to calculate the total elapsed time for adding 100,000 elements to a list.

    The result shows that it takes negligible time to run the code (0.0 seconds compared to 0.006 seconds for the append() operation above).

    The extend() method is the most concise and fastest way to concatenate lists.

    But there’s still more…

    4. List Concatenation with Asterisk Operator *

    There are many applications of the asterisk operator (read this blog article to learn about all of them). But one nice trick is to use it as an unpacking operator that “unpacks” the contents of a container data structure such as a list or a dictionary into another one.

    The code shows that the asterisk operator is short, concise, and readable (well, for Python pros at least). And the nice thing is that you can also use it to concatenate more than two lists (example: l4 = [*l1, *l2, *l3] ).

    But how about its performance?

    Performance:

    You’ve seen before that extend() is very fast. How does the asterisk operator compare against the extend() method? Let’s find out!

    I measured the start and stop timestamps to calculate the total elapsed time for concatenating two lists of 1,000,000 elements each.

    The result shows that the extend method is 32% faster than the asterisk operator for the given experiment.

    To merge two lists, use the extend() method which is more readable and faster compared to unpacking.

    Okay, let’s get really nerdy—what about external libraries?

    5. List Concatenation with itertools.chain()

    Python’s itertools module provides many tools to manipulate iterables such as Python lists. Interestingly, they also have a way of concatenating two iterables. After converting the resulting iterable to a list, you can also reach the same result as before.

    The result is the same. As readability is worse than using extend(), append(), or even the asterisk operator, you may wonder:

    Is it any faster?

    Performance:

    You’ve seen before that extend() is very fast. How does the asterisk operator compare against the extend() method? Let’s find out!

    I measured the start and stop timestamps to calculate the total elapsed time for concatenating two lists of 1,000,000 elements each.

    The result shows that the extend() method is 5.6 times faster than the itertools.chain() method for the given experiment.

    Here’s my recommendation:

    Never use itertools.chain() because it’s not only less readable, it’s also slower than the extend() method or even the built-in unpacking method for more than two lists.

    So let’s go back to more Pythonic solutions: everybody loves list comprehension…

    6. List Concatenation with List Comprehension

    What a mess! You’d never write code like this in practice. And yet, tutorials like this one propose this exact same method.

    Do we get a speed performance out of it?

    Performance:

    You’ve seen before that extend() is very fast. How does the asterisk operator compare against the extend() method? Let’s find out!

    I measured the start and stop timestamps to calculate the total elapsed time for concatenating two lists of 1,000,000 elements each.

    The result shows that the extend() method is an order of magnitude faster than using list comprehension.

    Summary

    To concatenate two lists l1, l2, use the l1.extend(l2) method which is the fastest and the most readable.

    Want to use your skills to create your dream life coding from home? Join my Python freelancer webinar and learn how to create your home-based coding business.

    How to concatenate lists in python. Смотреть фото How to concatenate lists in python. Смотреть картинку How to concatenate lists in python. Картинка про How to concatenate lists in python. Фото How to concatenate lists in python

    While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

    To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

    His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

    7 Ways to Concatenate Two or More Lists in Python

    In Python, we use lists in almost every program. While working with Python lists, we need to concatenate two or more lists on several occasions. In this article, we will look at various ways to concatenate two lists in Python. We will also discuss the efficiency of all the approaches in terms of time and memory usage so that you can choose the best way to concatenate lists in your programs in Python.

    Concatenate Lists Using the append() Method in Python

    The first way to concatenate two lists in Python is to use a for loop with the append() method. When executed on a list, the append() method accepts an element as its input argument and adds it to the existing list, as shown in the following example.

    Please enable JavaScript

    The append() method is normally used to add a single element to an existing list. To concatenate two lists using the append() method, we will add each element of the second list to the first list using the append() method and a for loop as follows.

    Concatenate Lists Using the + Operator in Python

    Instead of using the append() method, we can use the + operator to concatenate two lists in Python. Just like we concatenate two strings using the + operator in Python, we can concatenate two lists as follows.

    Using the + operator to concatenate two lists has the advantage of concatenating more than two lists using a single statement. For instance, we can concatenate four lists in Python using the + operator as follows.

    Concatenate Lists Using the extend() Method in Python

    We can also use the extend() method to concatenate two lists in Python. When executed on a list, the extend() method accepts any iterable object like list, set, or tuple and adds the elements of the iterable object to the end of the list.

    To concatenate two lists, we can execute the extend() method on the first list and pass the second list as an input argument to the extend() method as follows.

    Here, we have appended the elements of list2 to list1 using the extend() method.

    Concatenate Lists Using the += Operator in Python

    The += operator is an unpopular but efficient tool to concatenate two lists in Python. It works similarly to the extend() method. The syntax for using the += operator is as follows.

    To concatenate two lists using the += operator, we will use the first list as the oldList and the second list as the iterable as follows.

    Concatenate Lists Using Packing and Unpacking in Python

    To concatenate two or more lists using the packing and unpacking operations, we will first unpack the lists using the * operator. Then, we will pack the unpacked elements of the lists into a new list as follows.

    Here, you can pack the elements of any number of lists into a single list. Thus, this method is also useful for concatenating more than two lists. For instance, you can concatenate four lists in a single statement as follows.

    Concatenate Lists Using the itertools.chain( ) Function in Python

    In Python, we use the chain() function from the itertools module to create iterators. The chain() function, when executed, accepts multiple iterable objects as its input arguments, chains all the elements in a single iterator, and returns the iterator. To use the chain() function, you can import the itertools module as follows.

    Concatenate Lists Using List Comprehension in Python

    On some occasions, list comprehension is a better alternative to for loop while working with lists in Python. We can also concatenate two or more lists using list comprehension. The syntax for the same is as follows. newList= [element for temp_list in [list1, list2] for element in temp_list] Here,

    We can use list comprehension to concatenate two lists in Python as follows.

    If you are not able to understand the syntax of the list comprehension above, the for loop in the following program is equivalent to the list comprehension syntax.

    We can also concatenate more than two lists using list comprehension. We will just have to insert the input lists in the list of lists as follows.

    What Method Should You Use to Concatenate Lists in Python?

    Conclusion

    In this article, we have discussed seven approaches to concatenate two or more lists in Python. We have also discussed what approach you can use based on your requirements to write an efficient program.

    Источники информации:

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *