Python appending two lists

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.

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.

Читайте также:  Php check request content type

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.

Источник

Merge Two Lists in Python

Python Certification Course: Master the essentials

A list is a data structure in Python that contains a sequence of elements. We can have many lists in our code, which sometimes we may need to merge, join, or concatenate. Merging a list is very useful in many ways, and through this article, we will see the various ways we can merge two lists in Python.

Merging Two Lists in Python

Merging lists means adding or concatenating one list with another. In simple words, it means joining two lists. We can use various ways to join two lists in Python. Let us discuss them below:

1. Using append() function

One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn’t return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.

Explanation:

  • In the above code, we declare two lists, ls1 and ls2 .
  • We iterate over ls2 and append its elements to ls1 using our python’s append method.

2. Using the ‘+’ Operator

This is the simplest way to merge two lists in Python. ‘+’ operator is a multipurpose operator, which we can use for arithmetic calculations and for merging purposes, strings, lists, etc.

Explanation:

  • We defined our lists ls1 and ls2
  • Then, we merged them using the ‘+’ operator in Python.
  • The use of + operator adds the whole of one list behind the other list.
Читайте также:  Времена английский языка html

3. Using List Comprehension

We can merge two lists in Python using list comprehension as well. List comprehension offers a shorter and crisper syntax when we want to create a new list based on the values of an existing list. It may also be called an alternative to the loop method.

Explanation:

  • In the above example, first, this line is executed for n in (num1,num2) , which will return [[1, 2, 3], [4, 5, 6]] .
  • After that, we pick one element at a time from the above lists. Hence we do for x in n .
  • Finally, we get our desired result by storing the value of x in the list: [x for n in (num1,num2) for x in n]

4. Using the extend() method

The extend() method adds all the elements of an iterable (list, tuple, string, etc.) to the end of the list. It updates the original list itself. Hence its return type is None. It can be used to merge two lists in Python.

Explanation:

  • We defined our lists and passed them to our extend method in python
  • extend basically, extended the list2 to the end of list1 . The size of the list increased by the length of both lists.
  • Also, extend updated our ls1 directly.

5. Using iterable unpacking operator *

An asterisk * denotes iterable unpacking. The unpacking operator takes any iterable(like list, tuple, set, etc.) as a parameter. Then the iterable is expanded into a sequence of items included in the new tuple, list, or set at the site of the unpacking.

Any no. of lists can be concatenated and returned in a new list using this operator. Hence it can be used to merge two lists in Python.

Note: works only in Python 3.6+ .

Explanation:

  • The * first unpacks the contents of ls1 , ls2 , and ls3 and then creates a list from its contents.
  • Then, all the items of our iterables will be added to our new list ls .

Conclusion

  • Merging two lists in Python is a common task when working with data.
  • There are several ways to merge two lists in Python, depending on the specific requirements of the task.
  • One of the simplest ways to merge two lists is to use the «+» operator to concatenate them.
  • Another approach is to use the «extend()» method to add the elements of one list to another.
  • You can also use the «zip()» function to combine the elements of two lists into a list of tuples.
  • If the lists contain duplicates, you can use the «set()» function to remove them before merging.
  • In some cases, you may need to merge lists while preserving the order of elements. This can be done using the «sorted()» function or a custom sorting function.
  • When merging large lists or working with memory-intensive data, it’s important to consider the efficiency of the merging method.

Источник

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