Home > Mobile >  Trouble in the for loop while printing the list
Trouble in the for loop while printing the list

Time:02-01

Here I'm trying to use a for loop in list's, but whenever I'm using range with for loop, I'm getting this error

for i in range(listType):
TypeError: 'list' object cannot be interpreted as an integer
 
KeyboardInterrupt

But when I'm trying len() function with the range in for loop , there's no error. Can anyone explain me ,like what's happening here?

Here's the piece of code I'm trying to run-

listType = ['US', 'UK', 'India', 'China']
for i in range(listType):
    print(listType[i]) 

CodePudding user response:

The range() function accepts an integer input. So since listType is a list it throws an error because "'list' object cannot be interpreted as an integer."

range(n) wants to create a range object from 0 to n but it cannot if n is not a type that can be within a range (integer). len() however, returns an integer that is equal to the length of the list, therefore range() is happy with the integer input.

It would be simpler to instead use this:

listType = ['US', 'UK', 'India', 'China']
for i in listType:
    print(i)

Output:

US
UK
India
China

CodePudding user response:

Remember that Python's for loops are like JavaScript's forEach loops:

for i in listType:
    print(i)

The range constructor you put in your code is often used to simulate a pure for loop in Python:

for i in range(len(listType)):
    print(listType[i]) # This produces the same output

In Python range is an iterable class, its constructor works like this:

range(start, end)
for i in range(1, 4):
    print(i) # 1 - 2 - 3

Anyway it takes two int arguments (there are three arguments, but only one is compulsory), so you can't pass an iterable (in your case a list) as the first positional argument of range.


When you want to iterate over an iterable, it's a better practice to use the first code I provided.

When you need to access the index during the iteration, it's a better practice to do like this:

for index, element in enumerate(listType):
    print(f"{element} at index {index}")

CodePudding user response:

you can use len() to do this:

listType = ['US', 'UK', 'India', 'China']
for i in range(len(list Type)):
    print(listType[i]) 

Or using a more easy way:

listType = ['US', 'UK', 'India', 'China']
for i in listType:
    print(i) 
  •  Tags:  
  • Related