Python merge arrays one by one

Concatenate or Merge Two or Multiple lists in Python?

Combining strings or characters in programming is called concatenation. In Python, concatenation can be performed on numbers, strings and elements of a list. For example, you can add a string “Hey” and another string “there!” to form a new string “Hey there!”. You can also add two numbers such as 2 and 5 to get a result 7. The most common form of concatenation is by using the + operator.

Concatenating or merging two or multiple lists is a common operation of a programmer. In this tutorial, we will concatenate lists with and without duplicate elements.

1) Using + Operator

Its a very common operator to concatenate lists it simply adds list behind another list.

# Python program to merge lists # Using + Operator # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] list3 = [1,5,33,2,34,46] # merge lists using + Operator newlist = list1 + list2 + list3 # Print output print('Merged List: ',newlist) 
Merged List: [2, 3, 4, 2, 2, 4, 5, 6, 7, 34, 56, 1, 5, 33, 2, 34, 46]
  • It retains the order of list elements
  • Contain duplicate elements
  • Concatenated two or more lists
Читайте также:  Жир питона при ожоге

Explanation

Here, the three lists are combined together using + operator. This is used because the + operator is one of the easiest ways to combine multiple lists into a single one.

2) Using extend() Function

extend() function is also used to concatenate lists, it simply adds the whole list at the end of the first list.

# Python program to concatenate lists # Using extend function # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] list3 = [4,67,2,2,4,66] # concatenate lists using extend() list1.extend(list2) list1.extend(list3) # Print output print('Concatenated List: ',list1)
Concatenated List: [2, 3, 4, 2, 2, 4, 5, 6, 7, 34, 56, 4, 67, 2, 2, 4, 66]
  • It retains the order of list elements
  • Contain duplicate elements
  • It only concatenates two lists; if you want to concatenate more then two lists, then you need to use extend() function multiple times, as shown in the above example.

Explanation

In this program, the extend() method is used for concatenating all three lists together. You can see that the extend() method is used two times for merging the second and third list with the first list. As mentioned earlier, the method cannot add more than two lists. Thus it is used two times for adding the first list with the second and third list.

3) Using (*) Operator

(*) Operator works the same as (+) operator, with this we can concatenate to or more list it works with Python 3.6+ versions.

# Python program to merge lists # Using * Operator # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] list3 = [1,5,33,2,34,46] # merge lists using * Operator newlist = [*list1, *list2, *list3] # Print output print(Concatenated List: ',newlist)
Concatenated List: [2, 3, 4, 2, 2, 4, 5, 6, 7, 34, 56, 1, 5, 33, 2, 34, 46]
  • It retains the order of list elements
  • Contain duplicate elements
  • Concatenated two or more lists
Читайте также:  Multivariate linear regression python

Explanation

Here the (*) operator is used for merging the three lists together while maintaining the order of the elements. The (*) operator is utilized here as multiple lists can be easily added using it.

4) Using itertools.chain()

# Python program to concatenate lists # Using itertools import itertools # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] list3 = [1,5,33,2,34,46] # Concatenate lists using itertools newlist = list(itertools.chain(list1, list2, list3)) # Print output print('Concatenated List: ',newlist)
Concatenated List: [2, 3, 4, 2, 2, 4, 5, 6, 7, 34, 56, 1, 5, 33, 2, 34, 46]
  • Works with numpy array
  • It retains the order of list element
  • Contain duplicate elements
  • Concatenated tow or more lists

Explanation

In the first line, the import keyword is used to load the itertools module. The variables list1, list2 and list3 are assigned values [2,3,4,2,2], [4,5,6,7,34,56] and [1,5,33,2,34,46] respectively. Then, a newlist variable is assigned the concatenated values of the three lists.

In the next line, the itertools.chain() method is passed the arguments of list1, list2 and list3. This method takes multiple arguments and returns a single sequence of items. So, the chain() method concatenates all three lists. The result of the method call is converted into a list using the list() method.

The newlist variable is printed in the last line of the program using the code print(‘Concatenated List: ‘,newlist).

5) Using Native Function

To concatenate two lists, we will first traverse the second list using a for loop. We will keep appending the elements of this list to the first list. As a result, the two lists will be added.

# Python program to concatenate lists # Using for loop and append function # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] # merge list using for loop and append function for x in list2 : list1.append(x) # Print output print('Concatenate List: ',list1)
Concatenate List: [2, 3, 4, 2, 2, 4, 5, 6, 7, 34, 56]

Explanation

Let us try to understand this code. Here, a for loop is used for adding the two lists using the append() method. This process is used as the append() method adds a single element to the end of a list. Thus, each element of the list2 is added to list1, one by one using the for loop.

Single Line Code Example:

# Python program to concatenate lists # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] list3 = [1,5,33,2,34,46] # Concatenate lists newlist = [y for x in [list1, list2, list3] for y in x] # Print output print(Concatenated List: ',newlist)
Concatenated List: [2, 3, 4, 2, 2, 4, 5, 6, 7, 34, 56, 1, 5, 33, 2, 34, 46]

Explanation

We can observe that the shorthand version of a for loop is used here for concatenation. This list comprehension technique is used to avoid writing multiple inner loops, as there are three lists that have to be added. As a result, the process is fast and efficient.

Merge or Concatenate Lists Without Duplicates

From all the above examples, we can see that the final concatenate list has duplicate elements, if we want to remove duplicate from the list then we need to convert the list to “ set ” and then convert back to “ list .”

# Python program to Concatenate lists # Using + Operator # Initializing lists list1 = [2,3,4,2,2] list2 = [4,5,6,7,34,56] list3 = [1,5,33,2,34,46] # Concatenate lists using + Operator newlist = list1 + list2 + list3 # Convert final list to set() and then set to list() newlist = list(set(newlist)) # Print output print('Concatenated List Without Duplicate: ',newlist) 
Concatenated List Without Duplicate: [1, 2, 3, 4, 5, 6, 7, 34, 33, 46, 56]

Explanation

You can see that the main aim of the program is used to merge three lists that do not have duplicate elements. So, after concatenating the lists using a + operator, the resultant list is passed to the in-built set() method. As Python sets do not have any duplicate elements, this removes all the duplicates from the concatenated list. As we require a list, this set is converted into a list using the list() method.

Conclusion

Concatenation is one of the easiest ways to combine list elements or strings while codding in Python. But while using the chains() method, import the itertools module using the import statement. Additionally, you can also use methods such as join() to concatenate two strings.

  • Python Training Tutorials for Beginners
  • Python Continue Statement
  • Python lowercase
  • Python map()
  • Python String Replace
  • Python String find
  • Top Online Python Compiler
  • Python : end parameter in print()
  • Python String Concatenation
  • Python Pass Statement
  • Python Enumerate
  • Python New 3.6 Features
  • Python input()
  • Python String Contains
  • Reverse Words in a String Python
  • Ord Function in Python
  • Python Reverse String
  • Convert List to String Python
  • Python Infinity
  • Pangram Program in Python

Источник

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.

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.

Источник

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