Home > Back-end >  Python - for loop: TypeError: 'int' object is not iterable
Python - for loop: TypeError: 'int' object is not iterable

Time:01-02

I am trying to use the code below to check if someone is allowed to ride a coaster. The first part is to create a 2D list and the second part is for the checking.

heights = [165, 154, 156, 143, 168, 170, 163, 153, 167]
ages = [18, 16, 11, 34, 25, 9, 32, 45, 23]

heights_and_ages = list(zip(heights, ages))
heights_and_ages = [list(info) for info in heights_and_ages]

can_ride_coaster = []
for info in heights_and_ages:
  for height, age in info:
    if height > 161 and age > 12:
      can_ride_coaster.append(info)

I get the error on the line

if height > 161 and age > 18:

I think it's because I use two variables bcs it's alright if I use one, but after searching online that doesn't seem to be a problem. How can I fix this?

CodePudding user response:

There does not seem to be any need for a nested loop here. Each element of heights_and_ages is a pair, and you want to loop through it unpacking each pair into height and age.

for height, age in heights_and_ages:
    if height > 161 and age > 12:
        can_ride_coaster.append((height,age))

This lends itself to a list comprehension:

can_ride_coaster = [(h,a) for (h,a) in heights_and_ages if h > 161 and a > 12]

Why does your code error?

Suppose info is [165, 18]. When you write

for height, age in info:

you are saying "loop through info and unpack each element to height, age".

In the first iteration of that loop, the element is 165, and you try to unpack that single int value to multiple variables. That is why you get int object is not iterable.

  • Related