Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

Glynys

  • 2 years ago

>>> a_list = [3,5,6,12] >>> new_list = [] >>> for x in a_list: if x % 2 == 0: print True if x % 2 != 0: print False print new_list 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: True True False False Or else: [True] [True][True] [True][True][False] etc. 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. . . .

  • This Question is Open
  1. ronin12
    • 2 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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

  2. wio
    • 2 years ago
    Best Response
    You've already chosen the best response.
    Medals 2

    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 ``` def iseven(x): return x % 2 == 0 ``` Then you would say: ``` newlist = [iseven(x) for x in oldlist] ```

  3. Glynys
    • 2 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    ronin12 and wi -- very helpful, thank you!

  4. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy