TypeError: object is not iterable when trying to iterate over a list

Question:

I have written a code that is supposed to iterate over a list of numbers and perform certain operations on each element. However, I’m getting the following error message: ‘TypeError: object is not iterable’. Here is the relevant snippet of code:

my_list = 123
for element in my_list:
    Perform operations on each element

I don’t understand why I’m getting this error since I believe I have a list. What am I doing wrong, and how can I fix this issue?

Thank you in advance for your help!"

In this example, the problem is clearly described, and the relevant code snippet is provided to give context to the issue.

I tried it with integers too but i didnt expected anything

Asked By: Latif

||

Answers:

Integers aren’t iterable. if you want to iterate over an integer you first need to convert it to an iterable object like a string or list. You could do something like this:

my_list = 123
for element in str(my_list):
    Perform operations on each element
Answered By: CumminUp07

m_list = 123 is not a list actually, it’s a single variable that holding an integer value.
For creating list you can do something Like below:

my_list = [1, "Hello", 3.4]

Answered By: Hassam Chaudhary
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.