I have tried the following:
vrs = [('first text', 1),
('second text', 2),
('third text', 3),
('fourth text', 4),
('fifth text', 5),
('sixth text', 6),
('seventh text', 7),
('eighth text', 8),
('ninth text', 9),
('tenth text', 10),
('eleventh text', 11),
('twelfth text', 12)
]
if all(vr is tuple for vr in vrs):
print('All are tuples')
else:
print('Error')
if set(vrs) == {tuple}:
print('All are tuples')
else:
print('Error')
The output is Error
for both.
Is there any way to check for this (i.e. check if every element in a list is a tuple) without a loop?
Use isinstance:
isinstance(object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
vrs = [('first text', 1),
('second text', 2),
('third text', 3),
('fourth text', 4),
('fifth text', 5),
('sixth text', 6),
('seventh text', 7),
('eighth text', 8),
('ninth text', 9),
('tenth text', 10),
('eleventh text', 11),
('twelfth text', 12)
]
all(isinstance(x,tuple) for x in vrs)
True
vrs = [('first text', 1),
('second text', 2),
('third text', 3),
('fourth text', 4),
('fifth text', 5),
('sixth text', 6),
('seventh text', 7),
('eighth text', 8),
('ninth text', 9),
('tenth text', 10),
('eleventh text', 11),
'twelfth text'
]
all(isinstance(x,tuple) for x in vrs)
False