Get ALL items in a python list?

it’s very easy to get the number of items in a list, len(list), but say I had a matrix like: [[1,2,3],[1,2,3]] Is there a pythonic way to return 6? Or do I have to iterate.

Answer

You can use chain

from itertools import chain
l = [[1,2,3],[1,2,3]]
len(list(chain(*l))) # give you 6

the expression list(chain(*l)) give you flat list: [1, 2, 3, 1, 2, 3]

Leave a Reply

Your email address will not be published. Required fields are marked *