-2

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

Catacoder
  • 3
  • 2
  • 1
    `ties` is not a valid `Python` object. Would you mind sharing your actual code? – Jan Aug 25 '20 at 14:53
  • It is because your `i` refers to `84` in first iteration. which `int` object, and in python you cannot iterate over integers. – Rahul Raut Aug 25 '20 at 15:02
  • It appear that you have typos in your first line where `ties` is defined. You are missing opening brackets for the second and third tuples (in front of the `84,4` and the `84,23`). The code cannot run as it is, please fix this. – Glenn Mackintosh Aug 25 '20 at 15:05

3 Answers3

0

A list comprehension filtered by isinstance, under the assumption that ties is actually the following object (as OP's is invalid syntax)

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})
]

count_tuples = len([o for o in ties if isinstance(o, tuple)])

prints: 3

dh762
  • 2,259
  • 4
  • 25
  • 44
0

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))
Dharman
  • 30,962
  • 25
  • 85
  • 135
Shrayani Mondal
  • 160
  • 1
  • 7
0

If you simply want to know the number of tuples inside the list, you only need this:

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})
]

res = len(ties)
# 3

If you want a list with the length of the tuples inside the list, you need to use:

res = [len(tie) for tie in ties]
# [3, 3, 3]
Ajordat
  • 1,320
  • 2
  • 7
  • 19