Home python Python error: “int object is not iterable”

# Python error: “int object is not iterable”

Author

Date

Category

Given 20 numbers that create a sequence. A few numbers
which go in a row are equal to each other. 1) Find and display the quantity
such numbers. 2) Print how many different numbers are in the sequence

Error:

``````for i in n: TypeError: 'int' object is not iterable
``````
``````import random
numbers = []
k = 0
for i in range(20):
n = random.randint(1, 20)
numbers.append(n)
print(n, end=',')
print()
for i in n:
if n[i] == n[i-1] == n[i+1]:
k += 1
print(k)
``````

Problem solution:

``````import random
numbers = [random.randint(1, 10) for _ in range(20)]
print(numbers)
k = 0
i = 0
while i in range(len(numbers)):
k_ = k
for j in range(i+1, len(numbers)):
if numbers[i] == numbers[j]:
k += 1
else:
break
if k != k_:
k += 1
i += k-k_
else:
i += 1
print(f'Total length of all series: {k}')
print(f'Various elements: {len(set(numbers))}')
``````

Result:

``````[7, 7, 1, 10, 2, 2, 7, 7, 8, 8, 2, 10, 7, 4, 4, 6, 1, 10, 8, 4]
Total length of all series: 10
Various elements: 7
``````

I don’t understand a bit what you need, but I tried to follow your code

``````import random
numbers = []
k = 0
for i in range(20):
n = random.randint(1, 20)
numbers.append(n)
print(n, end=',')
for i in range(len(numbers)):
try:
if numbers[i] == numbers[i-1] == numbers[i+1]:
k += 1
except IndexError:
pass
print("\n" + str(k))
``````

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.