6

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.

  • 3
    use: `l = [[1,2,3],[1,2,3]]` `sum(map(len, l))` to get the 6, but for you an item is a number, but an item for a list is just an item that can be another list, number, floating, object, etc. – eyllanesc Sep 29 '18 at 23:11
  • 1
    The operation you're looking for is "flatten" the list. Then take the length of the flattened list – eddiewould Sep 29 '18 at 23:12
  • Probably iteration is the most readable solution IMO – dvnguyen Sep 29 '18 at 23:12
  • https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – eddiewould Sep 29 '18 at 23:17
  • 2
    Whenever you're doing anything fancy with list, the answer is *always* "just use numpy". – o11c Sep 29 '18 at 23:18

4 Answers4

9

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]

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • Would this work if the Matrix was 3 dimensional as well ex `[[[1,2,3]]]` –  Sep 30 '18 at 00:49
1

Make the matrix numpy array like this

mat = np.array([[1,2,3],[1,2,3]])

Make the array 1D like this

arr = mat.ravel()

Print length

print(len(arr))
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1
l = [[1,2,3],[1,2,3]]    
len([item for innerlist in l for item in innerlist])

gives you 6

Khalil Al Hooti
  • 4,207
  • 5
  • 23
  • 40
0

You just need to flatten list. Numpy is the best option. Still if you want, you can use simple if/else to flatten and return length of list. Example,

list_1 = [1, 2, 3, 'ID45785', False, '', 2.85, [1, 2, 'ID85639', True, 1.8], (e for e in range(589, 591))]




def to_flatten3(my_list, primitives=(bool, str, int, float)):
    flatten = []
    for item in my_list:
        if isinstance(item, primitives):
            flatten.append(item)
        else:
            flatten.extend(item)
    return len(flatten)
   
print(to_flatten3(list_1))
14

[Program finished] 
Subham
  • 397
  • 1
  • 6
  • 14