Neel Sanghvi
Neel Sanghvi

Reputation: 1

How to add values into an empty list from a for loop in python?

The given python code is supposed to accept a number and make a list containing all odd numbers between 0 and that number

n = int(input('Enter number : '))
i = 0 
series = []
while (i <= n):
    if (i % 2 != 0):
        series += [i]
print('The list of odd numbers :\n')
for num in series:
    print(num)

Upvotes: 0

Views: 5912

Answers (2)

EricF
EricF

Reputation: 21

So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.

In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.

One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:

series.append(i)

Good luck with your learning!

Upvotes: 2

Austin
Austin

Reputation: 26039

Do a list-comprehension taking values out of range based on condition:

n = int(input('Enter number : '))

print([x for x in range(n) if x % 2])

Sample run:

Enter number : 10
[1, 3, 5, 7, 9]

Upvotes: 1

Related Questions