A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://builtin.com/data-science/merging-lists-in-python below:

Merging Lists in Python | Built In

In Python, a list is a data type that contains an ordered sequence of objects and is written as a series of comma-separated values between square brackets. Merging lists can be done in many ways in Python

7 Ways to Merge a List in Python
  1. Append method
  2. Extend method
  3. Concatenation
  4. Unpacking with asterisk (*) method
  5. Itertools.chain
  6. List comprehension
  7. For loop

Let’s explore the different methods in detail.

A tutorial on how to merge lists in Python. | Video: Enthought How to Merge a List in Python 1. Append
num1=[1,2,3]
num2=[4,5,6]
num1.append(num2)
print (num1)
#Output:[1, 2, 3, [4, 5, 6]]
2. Extend
num1=[1,2,3]
num2=[4,5,6]
num1.extend(num2)
print (num1)
#Output:[1, 2, 3, 4, 5, 6]
3. Concatenation Concatenating Two Lists Example
num1=[1,2,3]
num2=[4,5,6]
num3=num1+num2
print (num3)
#Output:[1, 2, 3, 4, 5, 6]
Concatenating Two or More Lists Example
num1=[1,2,3]
num2=[4,5,6]
num3=[7,8]
num4=[9,10]
num5=num1+num2+num3+num4
print (num5)
#Output:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4. Unpacking With Asterisk (*)

An asterisk * denotes iterable unpacking. Its operand must be iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list or set, at the site of the unpacking.

list1=[*list2,*list3]

It unpacks elements from the original lists into a new list.

num1=[1,2,3]
num2=[4,5,6]
num3=[*num1,*num2]
print (num3)
#Output:[1, 2, 3, 4, 5, 6]
5. Itertools.chain

Itertools.chain is used for creating an iterator from two or more iterablesitertools.chain(*iterables). It will accept iterables as an argument. It returns each item from the first iterable then proceeds to the next, until there are no more iterables left and no more elements to return.

import itertools
num1=itertools.chain([1,2,3],[4,5,6])
#Returns an iterator object
print (num1)#Output:<itertools.chain object at 0x029FE4D8>
#converting iterator object to list object
print(list(num1))#Output:[1, 2, 3, 4, 5, 6]
6. List Comprehension

List comprehension is used to create a new list based on existing iterables. It’s used to write complex functionality in a single line of code. It creates a new list based on the existing values from the iterables.

Syntax for List Comprehension
new_list= [expression for element in iterable if condition]
Joining Two lists Using List Comprehension 
num1=[1,2,3]
num2=[4,5,6]
num3=[x for n in (num1,num2) for x in n]
print (num3)#Output:[1, 2, 3, 4, 5, 6]
7. For Loop
num1=[1,2,3]
num2=[4,5,6]
num3=[]
for n in (num1,num2):
   for x in n:
       num3.append(x)
print (num3)
#Output:[1, 2, 3, 4, 5, 6]

More on PythonAn Introduction to Python Linked List and How to Create One

How to Join All Strings in a List
str.join(iterable)

I will join all the elements in the iterable and return a string. We can mention the separator to join the elements in the iterable.

Example 1

In this first example, we’re going to join all strings in the list when the separator is given as space.

num1=["Welcome", "to", "python", "programming", "language"]
num2=" ".join(num1)
print (num2)
#Output:Welcome to python programming language
Example 2

In the second example, we’re going to join all strings in the list when the separator is given as -.

num1=["1","2","3"]
num2="-".join(num1)
print (num2)
#Output:1-2-3
How to Remove Duplicate Elements While Merging Two Lists

Python sets don’t contain duplicate elements. To remove duplicate elements from lists we can convert the list to set using set() and then convert back to list using list() constructor.

Note: Converting to a set removes duplicates but also loses original order. Use dict.fromkeys() or collections.OrderedDict if order matters.

num1=[1,2,3,4,5]
num2=[1,3,5,7,9]
num3=list(set(num1+num2))
print (num3)
#Output:[1, 2, 3, 4, 5, 7, 9]

More on Python5 Ways to Remove Characters From a String in Python

Speed Comparison of Ways to Merge Lists in Python
time.time() → float

Return the time in seconds since the epoch as a floating-point number.

1. Append Method Merge List Time 
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start=time.time()
num1.append(num2)
print (time.time()-start)
#Output:0.0019817352294921875
2. Extend Method Merge List Time
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start1=time.time()
num1.extend(num2)
print (time.time()-start1)
#Output:0.00701141357421875
3. Concatenation Operator Merge List Time
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start2=time.time()
num1+num2
print (time.time()-start2)
#Output:0.014112710952758789
4. Unpacking Method Merge List Time
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start3=time.time()
[*num1,*num2]
print (time.time()-start3)
#Output:0.020873069763183594
5. itertools.chain() Merge List Time
import itertools
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start4=time.time()
num3=itertools.chain(num1,num2)
list(num3)
print (time.time()-start4)
#Output:0.045874595642089844
6. List Comprehension Merge List Time
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start5=time.time()
num3=[x for n in (num1,num2) for x in n]
print (time.time()-start5)
#Output:0.06680965423583984
7. For Loop Merge List Time
import time
num1=list(range(1,1000000))
num2=list(range(1000000,2000000))
start5=time.time()
num3=[]
for n in (num1,num2):
   for x in n:
       num3.append(x)
print (time.time()-start5)
#Output:0.23975229263305664
Merge List Method Time Comparisons Time to merge lists in Python comparison bar chart. | Image: Indhumathy Chelliah Time taken to merge lists in Python graph key. | Image: Indhumathy Chelliah

Note: Although append() may be faster than other merge list methods, it doesn’t flatten or merge lists the way the other methods do.

More on PythonPython Tuples vs. Lists: When to Use Tuples Instead of Lists

Merging Lists in Python Tips

What’s the difference between append() and extend() in Python?

In Python append() adds an entire object (like a list) as a single element to the end of the list, while extend() adds each item from an iterable individually, increasing the length of the original list accordingly.

Does the + operator modify the original list?

No. In Python, using the + operator to merge lists creates a new list and does not modify the original lists.

What is the fastest way to merge two large lists in Python?

Among the tested list merge methods in Python, append() has the fastest runtime, but it does not flatten the lists. For actual merging of elements, extend() was faster than unpacking, + or loops.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4