Search code examples
pythonpython-3.xnetworkxmesa

Unable to count items inside a tuple inside a list


I currently have a list of tuples and I'm trying to count the number of tuples inside my list so I can do other computations but I can't seem to get it to work.

ties = [(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}),
        (84,4,{'variable1' : -0.18855, 'variable2': -0.6458}), 
        (84,23,{'variable1' : 0.05144, 'variable2': -0.7581})]

ties = list((int(j) for i in ties for j in i))

res = len(ties) 

#alternatively I also tried

from itertools import chain 

res = len(list(map(int, chain.from_iterable(ties))))

The above (both) would throw an error TypeError: 'int' object is not iterable and I don't understand why. Thoughts?

Thanks in advance!

*** Edit ***

Fixed the syntax error, now it works, thank you everyone for your suggestions


Solution

  • Tuples can't be iterated over. Hence you are getting the error when trying to execute the code. Also, the following code that you posted is giving a syntax error.

    ties = [(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}), 84,4,{'variable1' : -0.18855, 'variable2': -0.6458}), 84,23,{'variable1' : 0.05144, 'variable2': -0.7581})]
    

    You seemed to have missed the opening brackets before 84,4 and again before 84,23.

    Try the following:

    ties = [(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}), (84,4,{'variable1' : -0.18855, 'variable2': -0.6458}), (84,23,{'variable1' : 0.05144, 'variable2': -0.7581})]
    
    ties_len = list((len(i) for i in ties))