Hello All

I'm not quite sure you can do this but it seems to me like something python is probably able to do. Basically, I need to assert that somewhere in my list of lists i have a '2', and a '1'. Now my lists in the biglist are all the same length. By which i mean that len(BigList) == len(BigList[i+1] for all valid indicies i.

I was just thinking something like this:


[element for element in SmallList for SmallList in BigList]

I understand why this doesn't work, but for some reason, i'm pretty sure that it can be done in python. It just seems to cohere with the python way of doing things.

I may be wrong, but i thought i'd ask. For now i have to settle for this ugly alternative:

FlattenedList = []
for SmallList in BigList:
    for element in SmallList:
        FlattenedList.append(element)
assert FlattenedList.__contains__('2'), "Does not contain 2."
assert FlattenedList.__contains__('1'), "Does not contain 1."

Use itertools.

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))

Edited 5 Years Ago by woooee: n/a

Use itertools.

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))

Perfect. Thanks! Just for my own edification though, is it possible to do it with a list comprehension similar to my example?

Thanks again,
Khodeir

Simply (and looks to me your original one should be same):

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))
print [element for sub in x for element in sub]

Output:

['foo', 'bar', 'baz', 'quux', 'tup_1', 'tup_2', 1, 2]
['foo', 'bar', 'baz', 'quux', 'tup_1', 'tup_2', 1, 2]

Simply (and looks to me your original one should be same):

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))
print [element for sub in x for element in sub]

Output:

['foo', 'bar', 'baz', 'quux', 'tup_1', 'tup_2', 1, 2]
['foo', 'bar', 'baz', 'quux', 'tup_1', 'tup_2', 1, 2]

Thank you, pyTony, that's exactly what i was looking for.

This question has already been answered. Start a new discussion instead.