I'm using python 3.6. I came across the below way to flatten the nested list using sum
:
a = [[1, 2], [3, 4], [5, 6]]
sum(a,[])
which returns:
[1,2,3,4,5,6]
What exactly is going on here? Sum takes an iterable, in this case a list, and a start value. I don't understand what python reads to flatten the list.
Could make it more concise, def flatten(x): return [a for i in x for a in flatten(i)] if isinstance(x, collections. Iterable) else [x] - but readability might be subjective here.
So, the most efficient way to do this is to use list(chain.from_iterable(newlist)), in Python 2.7. So, be it Python 2.7 or 3.3, use list(chain.from_iterable(newlist)) to flatten the nested lists.
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: NestedIterator (List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
NestedIterator (List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next () Returns the next integer in the nested list.
Importing itertools to your python program gives you access to its in-built function called itertools.chain (), which merges various lists of the nested list into a unified list. The 2-D list to be flattened is passed as an argument to the itertools.chain () function. 7. Flatten List in Python Using Reduce Function:
This is just a result of how Python interprets addition of lists. From the docs
sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns the total.
Since sum
starts by adding the first element of the iterable to the start
argument, you have:
[] + [1, 2] = [1, 2]
Then it continues adding items from the iterable:
[1, 2] + [3, 4] = [1, 2, 3, 4]
[1, 2, 3, 4] + [5, 6] = [1, 2, 3, 4, 5, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With