0

My specifications were:

  • Create an empty list called to_ten.
  • Next, write a for loop that iterates over the numbers from 1 to 10 using the range() function and appends to the list whether the number is even or odd.

You should end up with a list containing 10 elements with each entry being even or odd.

This is my code:

to_ten = []
for x in range(11):
    to_ten.append(x%2==0)
to_ten

So far I am getting correctly whether they are even or odd but it is giving me true/false instead of simply saying even/odd for each number in my list.

Community
  • 1
  • 1
Anna
  • 19
  • 1
  • Does this answer your question? [Generating a list of EVEN numbers in Python](https://stackoverflow.com/questions/11233355/generating-a-list-of-even-numbers-in-python) – sushanth Jun 10 '20 at 03:10
  • 1
    @Sushanth, that link gives you a list of even numbers, not a list of indications as to whether each number was odd or even. – paxdiablo Jun 10 '20 at 03:11
  • that's because you are checking whether or not a condition is True or False or not, so that's what you're getting..you need to add something like - if its odd, append "odd" – Derek Eden Jun 10 '20 at 03:11
  • for the sake of fun, two other approaches would be: `['Even' if x%2==0 else 'Odd' for x in range(11)]` or `list(map(lambda x: 'Even' if x%2 == 0 else 'Odd', range(11)))` – Derek Eden Jun 10 '20 at 03:19

2 Answers2

0

I ran your code:

to_ten = []
for x in range(11):
    to_ten.append(x%2==0)
to_ten

which gives me: [True, False, True, False, True, False, True, False, True, False, True]

Now all you want is to have Even if it is True and Odd otherwise

You can use in-line if-else statement as follows

to_ten = ["Even" if i else "Odd" for i in to_ten ]
['Even','Odd','Even','Odd','Even','Odd','Even','Odd','Even','Odd','Even']

You can directly do it in your code as well

to_ten = []
for x in range(11):
    to_ten.append("Even" if x%2==0 else "Odd")
to_ten

Also you are iterating from 0 to 10 if you want to go from 1 to 10 it is range(1,11)

Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
0

You almost have it, you just need to:

  • realise that iterating from 1 to 10 involves starting at one; and
  • inserting what you want in the list rather than the boolean value.

For example:

to_ten = []
for x in range(1, 11):
    to_ten.append('even' if x % 2 == 0 else 'odd')
print(to_ten)

That gives:

['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

Of course, the Pythonic way is almost always with a list comprehension, though your specifications clearly call for appending to an initially empty list, so I wouldn't use this (it's good to know about it, however):

to_ten = ['even' if x % 2 == 0 else 'odd' for x in range(1, 11)]
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953