Flatten List

Hi All,

How could i reduce this to one script?

  1. repeat list 5 times.
  2. flatten list.
  3. find string and output result.


1 Like

Hi @Kulkul , thanks for the reply. Perhaps someone else can help?

Here is what I’ve done for a list.

I get stuck on the nested list, how can i flatten this?

Any help would be great. Cheers

Hi @Lknapton

I don’t fully understand what you are trying to achieve, but to flatten a nested list,
you can just iterate through it twice > iterate over sublists,and iterate through each item in sublist

If you are dealing with an unknown long nesting depth, you would need recursion, but that seem to be the case.

Here an example of how you can get to all the nested items

Here is an example of flattening, but also excluding/including based on a condition, similar to what you have done:


Another way:

lst = [["a", "b", "c", "d", "e"]] * 5
lst2 = [i for i in [j for i in lst for j in i] if "b" in i]

OUT = lst2

lst = [["a", "b", "c", "d", "e"]] * 5
func = lambda item : [j for i in lst for j in i]
lst3 = [i for i in func(lst) if "b" in i]

OUT = lst3

import itertools

lst = [["a", "b", "c", "d", "e"]] * 5
lst2 = list(itertools.chain(*lst))
lst3 = [item for item in lst2  if "b" in item]

OUT = lst3

The fact that you can doesn’t mean you should.
I personally like to avoid list comprehension for nested operations.
It’s easy to break into a loop first, then use comprehension on the nested level.

I find it this VERY hard to read.:confused:

lst2 = [i for i in [j for i in lst for j in i] if "b" in i]

Who says that?..


@Organon I think nested list comprehensions are tricky to read, especially for beginners.
I didn’t intend to sound rude or dismiss your reply as a valid solution

I actually thought @Lknapton had pasted an answer from somewhere else (your white thumbnail image tricked me)
so I wanted to encourage him to try a less complex solution

Ok, it’s just a misunderstanding.


Thanks for all the help