-1

i have a list with three lists inside it iam trying to turn it to one list that has all the items that were in the 3 seperated list and with the same order

so for example I have a list "B" which has 3 lists inside it. I ran for loop in a range of (len(B)-1) applying this command:

B[0]=B[0].extend(B[1])

But the value of B[0] became None . and I don't know why

small note: the problem that I'm solving is preventing me from using any if condition in my code

  • 3
    This may help flatten your list: https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists ; as for the problem you come upon, `.extend` is an inplace method, which returns None: https://stackoverflow.com/questions/11205254/why-do-these-list-methods-append-sort-extend-remove-clear-reverse-return – Swifty Aug 19 '23 at 12:06
  • I'd suggest a slightly different approach: https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable – Kenny Ostrom Aug 19 '23 at 13:55
  • "But the value of B[0] became None . and I don't know why" - because that's what `.extend` returns, and you assign that result. Please see the linked duplicate. – Karl Knechtel Aug 19 '23 at 15:36
  • "i have a list with three lists inside it iam trying to turn it to one list that has all the items that were in the 3 seperated list and with the same order" - then instead of asking about your approach tothe problem, you should simply ask about that task. – Karl Knechtel Aug 19 '23 at 15:39

1 Answers1

0

The extend list method destructively modifies the list and returns None. So the assignment

B[0]=B[0].extend(B[1])

first modifies B[0] by extending it, then replaces it with None due to the assignment. You can replace it with:

B[0].extend(B[1])

That will destructively modify B[0] by extending it with B[1]. It's equivalent to B[0] += B[1], which also destructively modifies B[0].

This explains what your code is currently doing, but it doesn't solve your problem. If you just want to create a new list which is the concatenation of the sublists, you can do:

new_list = sum(B, [])

This creates a new list consisting of the concatenation of the sublists.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • You can even replace it with `B[0].extend(B.pop(1))` to remove B[1] at the same time you extend B[0]. – Swifty Aug 19 '23 at 12:10