Home > front end >  If else multiple tuples in a list
If else multiple tuples in a list

Time:09-24

I am having an if method to check whether the [1] index value inside a tuple is less or equal to 255. While im feeding this method a single tuple inside a list it works eg [(0, 323)], but when im feeding the [(0, 323), (1, 1)] it doesn't.

if [i for i in a if i[1] <= 255]:
    print("a")
else:
    print("b")

Example if my values are [(0, 323)] it correctly prints b but when they change to a multiple tuple inside the same list [(0, 323), (1, 1)] it just prints a which is not correct. Any inputs please?

CodePudding user response:

Example if my values are [(0, 323)] it correctly prints b but when they change to a multiple tuple inside the same list [(0, 323), (1, 1)] it just prints a which is not correct. Any inputs please?

The behaviour is perfectly in line with the code:

[i for i in a if i[1] <= 255]

will return a list of all the tuples where the second item is under 255. For your second test case it returns [(1, 1)].

This is then interpreted in a boolean context, in Python collections are generally "truthy" if the collection is non-empty and "falsy" is empty. A list of one element is non-empty, therefore truthy, therefore "a".

If you want this to pass when all tuples have a second value under 255, then that's a job for... the all function.

# transform the comprehension because `all([])` is `True` which seems
# undesirable here
if all(thing <= 255 for _, thing in a):
    print("a")
else:
    print("b")

Incidentally, i is colloquially an index, since this is not the case here i should be avoided. Same with j.

For a genering element prefer e, or better provide a name which actually explains what the thing is.

CodePudding user response:

You are currently checking if there is ANY tuple in the list whose second item is less or equal to one. If that's what you want, any() would be better:

if any(each for each in a if each[1] <= 255):
    print("Yup, at least one tuple matched")
else:
    print("Nope, not a single one")

If you want to check if all the tuples matches, you use all().

If you want to check each item, you need to loop over the list:

for each in a:
    if each[1] <= 255:
        print(f"{each} matches")
    else:
        print(f"{each} does not match")
  • Related