-4

I was trying to merge a Python list that looks like this:

list1 = ["a", "b", "c", ["d", "f"]]

Hoping to get a list like this:

list2 = ["a", "b", "c", "d", "f"]

But in the end, the code was so long. Is there a fast and efficient way to do so in Python?

Here the for loop is involved. Is there a faster way, without for loops?

elpideus
  • 95
  • 1
  • 10
  • @VishalSingh Partially. The code is smaller but still for loops are involved. For lists with more than 5000 elements, this can become slow. Anyway, your suggestion was really useful. Thank you! – elpideus Apr 19 '21 at 09:41

1 Answers1

0

You can use iterables like this or item in sublist. Looking at the performance the latter is much quicker:

import time
import itertools

list1 = ["a", "b", "c", ["d", "f", ["g", "h"]]]

# example 1
t1 = time.time()
flat_list = list(itertools.chain.from_iterable(list1))
t2 = time.time()
print(flat_list)
print(t2-t1)
# ['a', 'b', 'c', 'd', 'f', ['g', 'h']]
# 3.0994415283203125e-06

# example 2
t1 = time.time()
flat_list = [item for sublist in list1 for item in sublist]
t2 = time.time()
print(flat_list)
print(t2-t1)
# ['a', 'b', 'c', 'd', 'f', ['g', 'h']]
# 2.1457672119140625e-06
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50