0

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]
JonSG
  • 10,542
  • 2
  • 25
  • 36
magerine
  • 43
  • 4
  • Are you extending bigger_list by a smaller `list` or by a single item? What is the `type` of `item.nest_items`? – JonSG May 04 '21 at 13:18

2 Answers2

3
bigger_list = [i.nested_item for i in items]
Rishin Rahim
  • 655
  • 4
  • 14
  • Given that `i.nested_items` suggests a type of `list`, I believe this answer produces a `list` of `list`s rather than `extend`ing a single `bigger_list` of items. – JonSG May 04 '21 at 13:21
0

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.

JonSG
  • 10,542
  • 2
  • 25
  • 36