1

I have a list made of tuple

liste_groupe=((image1, image2, image6),(image5, image4, image8, image7, image3, image9))

and i would like to have the number of element of all the tuple ie here the result would be 9

I have tried len(liste_groupe) but it gives me 2.

So what code should I write in order to have the number of all the element of all the tuples in a list ?

Laure D
  • 857
  • 2
  • 9
  • 16
  • What is the question? – Vedang Mehta Jun 02 '16 at 16:46
  • 1
    The number of elements regardless of containment level direct in outer sequence or inner (nested) sequence I understand. One solution is flattening and counting the result like described at http://stackoverflow.com/questions/5828123/nested-list-and-count and several other places ;-) – Dilettant Jun 02 '16 at 16:50

5 Answers5

2

There is no need to flatten the list in order to find the total length, and there is no need to use recursion if you already know the list is a simple 2D structure. This is all you need:

sum(map(len, liste_groupe))
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
1

Flatten a tuple of tuples into a list,

>>> liste_groupe=(('image1', 'image2', 'image6'),('image5', 'image4', 'image8', 'image7', 'image3', 'image9'))
>>> l = [item for t in liste_groupe for item in t]
>>> len(l)
9

# Or use itertools.chain
>>> import itertools
>>> l = list(itertools.chain(*liste_groupe))
>>> len(l)
9

If you only care about the number of elements,

>>> count = sum([len(t) for t in liste_groupe])
>>> count
9
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
0

You can follow a recursive approach:

def tuple_length( t ):
    if type(t) != tuple:
        return 1
    length = 0
    for element in t:
        length += tuple_length( element )
    return length

Now, tuple_length(liste_groupe) will return 9 as expected.

lcastillov
  • 2,163
  • 1
  • 11
  • 17
0

Recursion could accomplish this for you. With the following function the size of an n-dimensional tuple or list could be counted.

def calculate_size(data_set, size=0):
    for i in data_set:
        if isinstance(i, tuple) or isinstance(i, list):
            size += calculate_size(i)
        else:
            size += 1
    return size
TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19
0

Will work for a single nested list. For deeper or irregularly nested lists, you'll need a recursive function that uses chain.

from itertools import chain

cnt = len(list(chain.from_iterable(list_group)))
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118