Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How do I concatenate two lists in Python?

Solution:

If you want to concatenate two lists, you can do so by using the + operator. The * operator is also used to repeat a list a specified number of times. Here’s an example.


#Here is the example showing - 
#working of + and * operator.
#We have a sample list.
sample = [10, 20, 30]

#Adding new list in above one using + operator.
> print(sample + [40, 50, 60])

#Repeating the list 5 times using * operator.
> print(["Hey !!"] * 4)

Output: 
[10, 20, 30, 40, 50, 60]
['Hey !!', 'Hey !!', 'Hey !!', 'Hey !!']

There are, however, various techniques, such as

#’ itertools.chain() function

The itertools.chain() method accepts different iterables as parameters, such as lists, strings, tuples, and so on, and yields a sequence of them as output.



import itertools
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 42]

res = list(itertools.chain(list1, list2))

print ("Concatenated list: \n " + str(res))

# Python List Comprehension 

It goes over the list element by element using a for loop. The inline for loop shown below is similar 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))

Output: Concatenated list:

[10, 11, 12, 13, 14, 20, 30, 42]

# Naive method

A for loop is used to explore the second list in the Naive technique. The elements from the second list are then added to the first 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))

Output:

List1 before Concatenation:

[10, 11, 12, 13, 14]

Concatenated list, i.e., list1 after concatenation:

[10, 11, 12, 13, 14, 20, 30, 42]

For more details, visit our blogs.