Concatenate elements lists python

7 ways to concatenate two lists in Python

In this Python tutorial, we will understand the implementation of Python Concatenate List.

In Python, we can concatenate lists using the following 7 methods.

  1. Using append()
  2. Using + operator
  3. Using += operator
  4. Using list comprehension
  5. Using extend()
  6. Using * operator
  7. Using itertools.chain()

Python Concatenate List

Let us discuss all 7 methods to concatenate lists in Python. And first, we will discuss the conventional way by using the append() method.

Method 1: Python Concatenate List using append() method

One of the most common ways to concatenate lists in Python is by using the append() method. This method allows adding new elements at the end of the list.

  • So, if we want to concatenate 2 lists, we will use for loop to iterate over each element in the list.
  • In the end, we will use the append() method on the element to add that element to the last of the list.
Читайте также:  Javascript value in asp

Here is the approach for this in Python.

# Defining lists usa_states = ['California', 'Texas', 'Florida'] states = ['Alaska', 'Ohio', 'Hawaii'] # Using append() method for state in states: usa_states.append(state) # Printing the final list print(usa_states)

In the above example, we first defined 2 lists – usa_states and states respectively.

Then we used the for loop to iterate over each element given in the states list. And we will append that element to the usa_states list using the append() method.

['California', 'Texas', 'Florida', 'Alaska', 'Ohio', 'Hawaii']

Method 2: Python Concatenate List using + operator

Another way to concatenate multiple lists is by using the + operator. Generally, we use the + operator with numeric values to perform mathematical sums. However, the + operator is also used to concatenate strings.

And just like a string, we can also use the + operator with lists to concatenate lists in Python.

Here is an example of this in Python.

# Defining lists usa_states = ['California', 'Texas', 'Florida'] states = ['Alaska', 'Ohio', 'Hawaii'] # Using + operator concatenated_list = usa_states + states # Printing the final list print(concatenated_list)

In the example, we are concatenating list usa_states with states list using the + operator in Python.

And one we execute the above Python program, we will get the following result.

['California', 'Texas', 'Florida', 'Alaska', 'Ohio', 'Hawaii']

Method 3: Python Concatenate List using += operator

In the previous example, we have seen how to use the + operator to concatenate lists in Python. So, just like we use the + operator, we can also use the addition assignment (+=) operator for this task in Python.

Here is an example of this approach in Python.

# Defining lists usa_states = ['California', 'Texas', 'Florida'] states = ['Washington', 'Georgia', 'Hawaii'] # Using += operator usa_states += states # Printing the final list print(usa_states)

After executing the above Python program, we will get the following result.

['California', 'Texas', 'Florida', 'Washington', 'Georgia', 'Hawaii']

Method 4: Python Concatenate List using list comprehension

List comprehension in Python is a concise way to create a new list by performing some operation on each item of an existing Python list.

Moreover, we can also use the list comprehension method to concatenate multiple lists into one.

Here is an example of this task in Python.

# Defining lists usa_cities = ['New York', 'Chicago', 'San Diego'] cities = ['Philadelphia', 'Detroit', 'Atlanta'] # Using list comprehension concat_list = [city_y for city_x in [usa_cities, cities] for city_y in city_x] # Printing the final list print(concat_list)

In the above example, we have taken two different lists in Python. After this, we used list comprehension to concatenate both lists to form one concatenated list.

Here is the final result of the above Python program.

['New York', 'Chicago', 'San Diego', 'Philadelphia', 'Detroit', 'Atlanta']

Method 5: Python Concatenate List using extend()

The extend() method in Python is another way to concatenate multiple lists in Python. However, like the append() method, the extend() method modifies the list in place by adding all the elements of the specified list to the end of the original list.

An example related to the use of extend() method id shown below in Python.

# Defining lists usa_states = ['California', 'Texas', 'Florida'] states = ['Washington', 'Georgia', 'Hawaii'] # Using extend() method usa_states.extend(states) # Printing the final list print(usa_states)

In the above example, we used the extend() method on the usa_states list to concatenate all the elements of the states list as well.

However, once this Python program is executed, we will get the following result.

['California', 'Texas', 'Florida', 'Washington', 'Georgia', 'Hawaii']

Method 6: Python Concatenate List using * operator

Another way to concatenate lists in Python is by using the * operator within the list. The * operator is generally used in a Python list to unpack all its elements

We can understand the use of the * operator better with the help of the following example.

# Defining lists usa_cities = ['New York', 'Chicago', 'San Diego'] cities = ['Philadelphia', 'Detroit', 'Atlanta'] # Using * operator in list concat_list = [*usa_cities, *cities] # Printing the final list print(concat_list)

In the above example, we have taken two lists usa_cities and cities respectively. After this, we defined another list and within the square brackets, we defined both lists separately using a comma.

Additionally, to unpack each list, we used the * operator with each list in the square brackets.

After execution, we will get the following result.

['New York', 'Chicago', 'San Diego', 'Philadelphia', 'Detroit', 'Atlanta']

Method 7: Python Concatenate List using itertools.chain()

The itertools.chain() is a built-in function available under the itertools module. This function can take multiple iterable objects (like list, set, tuple, etc) as input, combines all of them, and return a single iterable object.

Let us see how to use this function in Python to concatenate multiple lists into one.

# Importing itertools import itertools # Defining lists usa_cities = ['New York', 'Chicago', 'San Diego'] cities = ['Philadelphia', 'Detroit', 'Atlanta'] # Using itertools concat_list = list(itertools.chain(usa_cities, cities)) # Printing the final list print(concat_list)

In this example, we have combined the usa_cities list with the cities list using itertools.chain(). After this, we converted the single iterable object into a list using the list() function.

The result of the above Python program is shown in the image below.

Python Concatenate List

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how Python concatenate list work. Moreover, we also 7 different methods to concatenate lists in Python. Here is the list of methods that we have covered in this tutorial.

  • Using append()
  • Using + operator
  • Using += operator
  • Using list comprehension
  • Using extend()
  • Using * operator
  • Using itertools.chain()

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

6 Ways to Concatenate Lists in Python

6 Ways to Concatenate Lists in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • concatenation (+) operator
  • Naive Method
  • List Comprehension
  • extend() method
  • ‘*’ operator
  • itertools.chain() method

1. Concatenation operator (+) for List Concatenation

The ‘+’ operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list1 + list2 print ("Concatenated list:\n" + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

2. Naive Method for List Concatenation

In the Naive method, a for loop is used to traverse the second list. After this, the elements from the second list get appended to the first list. The first list results out to be the concatenation of the first and the second list.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("List1 before Concatenation:\n" + str(list1)) for x in list2 : list1.append(x) print ("Concatenated list i.e. list1 after concatenation:\n" + str(list1)) 
List1 before Concatenation: [10, 11, 12, 13, 14] Concatenated list i.e. list1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

3. List Comprehension to concatenate lists

Python List Comprehension is an alternative method to concatenate two lists in Python. List Comprehension is basically the process of building/generating a list of elements based on an existing list.

It uses for loop to process and traverses the list in an element-wise fashion. The below inline for-loop is equivalent to a nested for loop.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [j for i in [list1, list2] for j in i] print ("Concatenated list:\n"+ str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

4.Python extend() method for List Concatenation

Python’s extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("list1 before concatenation:\n" + str(list1)) list1.extend(list2) print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1)) 

All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

list1 before concatenation: [10, 11, 12, 13, 14] Concatenated list i.e ,ist1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

5. Python ‘*’ operator for List Concatenation

Python’s ‘*’ operator can be used to easily concatenate two lists in Python.

The ‘*’ operator in Python basically unpacks the collection of items at the index arguments.

For example: Consider a list my_list = [1, 2, 3, 4].

The statement *my_list would replace the list with its elements at the index positions. Thus, it unpacks the items of the lists.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [*list1, *list2] print ("Concatenated list:\n " + str(res)) 

In the above snippet of code, the statement res = [*list1, *list2] replaces the list1 and list2 with the items in the given order i.e. elements of list1 after elements of list2. This performs concatenation and results in the below output.

Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

6. Python itertools.chain() method to concatenate lists

Python itertools modules’ itertools.chain() function can also be used to concatenate lists in Python.

The itertools.chain() function accepts different iterables such as lists, string, tuples, etc as parameters and gives a sequence of them as output.

It results out to be a linear sequence. The data type of the elements doesn’t affect the functioning of the chain() method.

For example: The statement itertools.chain([1, 2], [‘John’, ‘Bunny’]) would produce the following output: 1 2 John Bunny

import itertools list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list(itertools.chain(list1, list2)) print ("Concatenated list:\n " + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

Conclusion

Thus, in this article, we have understood and implemented different ways of Concatenating lists in Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью