>>> a_list = [3,5,6,12]
>>> new_list = 
>>> for x in a_list:
if x % 2 == 0:
if x % 2 != 0:
Anyone know why this won't work in Python shell? Trying to get a Boolean list from an integer list printed like this: [True, True, False, False]. I have gotten only:
This is question 7 on the Handout for OCW, ex. 2.12 of a 6.189 Gentle Intro to Python. Any insight appreciated. I am going on day 5 of not getting this. . . .
MIT 6.189 A Gentle Introduction to Programming Using Python (OCW)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
go into the python shell and type help(list.append) i feel this will help you immensely with what you are trying to accomplish
as a side note, you can type help(any built in object) into the python shell and you will get a list of all the methods(functions the object can do) for that object along with a quick description of how they work
When you print the values, it does not add them to your list. It just prints the values.
If you say `newlist = True` that also does not add `True` to the list, rather it discards the list. What you want to do is `list.append(True)` to add a Boolean to the list.
In addition, the `==` operator returns a Boolean result.
Thus simply putting `newlist.append(x % 2 == 0)` will fit your needs.
The best way to convert one list to another in python is to use list comprehension:
newlist = [ func(x) for x in oldlist ]
Where `func` takes some argument, changes it in some way, and returns the result.
For example, if you want to change an integer into a Boolean value based on whether it is even
return x % 2 == 0
Then you would say:
newlist = [iseven(x) for x in oldlist]