M
M
Mikhail Bolev2021-08-08 15:35:54
Python
Mikhail Bolev, 2021-08-08 15:35:54

How to organize a list into one line in Python?

How to write the list calculation code in one line? There is this code:

a_list = [1, [2, 3]]
new_list = []

for el in a_list:
    if isinstance(el, list):
          for inner_el in el:
               new_list.append(inner_el)
    else:
          new_list.append(el)

What is the correct way to replace it with one line? The following options do not work:
new_list = [inner_el if isinstance(el, list) else el for el in a_list for inner_el in el]

new_list = [el if not isinstance(el, list) else inner_el for el in a_list for inner_el in el]


Error: TypeError: 'int' object is not iterable

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-08-08
@Scorpion_MB

new_list = sum( (item if isinstance(item, list) else [item] for item in a_list) , [])

In fact, we turn each element of a_list into a list if it was not a list.
And then we summarize all these lists (this will be a concatenation operation).
Honestly, a simple for loop would be more readable (and faster, I think):
new_list = []
for item in a_list:
  if isinstance(item, list):
    new_list.extend(item)
  else:
    new_list.append(item)

But it will only work for one level of nesting. If you need more, use recursion or something similar.

A
aRegius, 2021-08-08
@aRegius

def flatten(items):
    for i in items:
        if isinstance(i, Iterable):
            yield from flatten(i)
        else:
            yield i

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question