Sunday, January 29, 2023

Concatenating Lists in Python

In this post we’ll see how to concatenate or join two lists in Python.

1. The best way to join two lists in Python is to use ‘+’ operator.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
#concatenating lists using + operator
num_list1 = num_list1 + num_list2
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

2. If you are asked to write a program to join two lists in Python without using any inbuilt function or operator then you can use for loop to iterate one of the list and add elements to another list.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
# iterate elements of list
for i in num_list2:
    num_list1.append(i)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

3. You can also join two lists using list comprehension in Python. Trick here is to create a list of lists and then flatten it.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
joined_list = [j for s in (num_list1, num_list2) for j in s]
print('Joined List-', joined_list)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

4. For joining two lists you can also use list.extend() method where you can pass another list as argument.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
num_list1.extend(num_list2)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

5. Using itertools.chain(*iterables) method that make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

This method returns itertools.chain object which is a generator iterator. By passing it to list() type constructor you can get joined list.

import itertools
num_list1 = ['a', 'b', 'c', 'd']
num_list2 = ['e', 'f', 'g', 'h']
joined_list = list(itertools.chain(num_list1, num_list2))

print('Joined List-', joined_list)

Output

Joined List- ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

That's all for this topic Concatenating Lists in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Named Tuple in Python
  3. Python for Loop With Examples
  4. String Length in Python - len() Function
  5. Keyword Arguments in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Python Program to Count Occurrences of Each Character in a String
  3. Interface in Python
  4. String Slicing in Python
  5. ArrayList in Java With Examples
  6. final Keyword in Java With Examples
  7. Just In Time Compiler (JIT) in Java
  8. Spring Job Scheduling Using TaskScheduler And @Scheduled Annotation

No comments:

Post a Comment