How can I write this in shorthand notion:
bigger_list=[]
for item in items:
new_list = item.nested_items
bigger_list += new_list
I have tried this, but it is not working
bigger_list += [item.nested_items for item in items]
How can I write this in shorthand notion:
bigger_list=[]
for item in items:
new_list = item.nested_items
bigger_list += new_list
I have tried this, but it is not working
bigger_list += [item.nested_items for item in items]
bigger_list = [i.nested_item for i in items]
It looks like you are attempting to make a single "merged" bigger_list
out of many smaller nested_items
lists (iterables). I believe you are looking to do:
bigger_list=[]
for item in items:
bigger_list.extend(item.nested_items)
There might be some temptation to try this via a comprehension as they tend to short and sweat:
bigger_list=[]
foo = [bigger_list.extend(item.nested_items) for item in items]
but comprehensions are for creating lists, not extending them. Don't use a comprehension like this. See : Is it Pythonic to use list comprehensions for just side effects?
If you were still very keen on using a comprehension, you could do the following but I think it is nowhere near as easy to follow as the simple for
:
bigger_list = [nested_item for item in items for nested_item in item.nested_items]
If the intension is that bigger_list
is to be a list of lists or that nested_items
is not an iterable, then the answer by @rishin is what you want.