-2

I am trying to write even numbers upto a limit into a list in Python using the following code

def odd_count(n):
    arr = list(50)
    for i in range(0,n,2):
        arr[i] = i
    return arr

I am gettting an error sayng TypeError: 'int' object is not iterable. What is wrong in this code? How can I fix it?

Mathew PM
  • 9
  • 1
  • 1

3 Answers3

4

This line raises the above mentioned exception

arr = list(50)

list expects an iterable object (something that has a __iter__() method). You are passing an int instead.

To create a list of size 50 you can use the * operator on a list:

arr = [None] * 50

This will create a list with all 50 elements set to None.

A more pythonic way to solve your problem is to pass the range object directly to the list constructor like:

def odd_count(n):
    return list(range(1,n+1, 2))

print(odd_count(50))
Anonta
  • 2,500
  • 2
  • 15
  • 25
0

You can initialize the list with brackets. In the for loop, use .append(). The final code should be

def odd_count(n):
    arr = []
    for i in range(0,n,2):
        arr.append(i)
    return arr
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

You can also use Python's list comprehension if you want to be Pythonic:

def even_numbers(n):
    return [i for i in range(0,n,2)]
Justin
  • 348
  • 3
  • 14
  • No-op listcomps aren't really Pythonic; if it's the identity transform with no filter, you'd just do `list(range(0, n, 2))`, which is faster (for all but the smallest inputs), shorter, and equivalent. – ShadowRanger Nov 29 '17 at 21:38