Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How flattening a nested list using `sum(iterable,[])` works? [duplicate]

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.

like image 618
RhythmInk Avatar asked Apr 17 '18 21:04

RhythmInk


People also ask

How do you flatten an irregular list in Python?

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.

How to flatten nested lists in Python?

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.

How to flatten a nested list of integers in Java?

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.

What is the use of nested iterator in Java?

NestedIterator (List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next () Returns the next integer in the nested list.

How to flatten list in Python using itertools?

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:


Video Answer


1 Answers

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]
like image 85
bphi Avatar answered Sep 30 '22 16:09

bphi