March 18th, 2013, 04:25 PM
If i in list
I am trying to check whether the input matches either of the fruits in the list or '1'
It works (prints "Correct!" and exits) if I type in '1' and press enter. However, when I type in 'apples' (for example, or any other fruit) it doesn't work and the loop repeats asking "Enter a fruit:".
It obviously works when i replace
if fru in [fruits, '1']
But that's not how I want to write the code. I want the code to be as short as possible
if fru in fruits or fru=='1'
Here is my code -
Any help would be appreciated! I couldn't find "in" anywhere in Python docs, or maybe I didn't check them correctly. Just started with python yesterday hehe.
from sys import exit
fruits = ['apples','oranges','bananas','mangos','strawberries']
fru = raw_input("Enter a fruit: ")
if fru in [fruits, '1']:
March 18th, 2013, 05:22 PM
The first thing that comes to mind is to make them both sets and then check if '1' is in their union:
Alternatively, you could flatten the [fruits, '1'] list by calling into the compiler.ast module, and use that:
if fru in set(fruits) | set(['1']):
To be quite frank though, I feel that your original if statement is the ideal one:
from compiler.ast import flatten
if fru in flatten([fruits, '1']):
Keep in mind The Zen of Python, particularly "Explicit is better than implicit" and "Readability counts". In your original if statement, it's very clear to see what the conditions are; whereas in the other two, even if it does the check against only one list (or set), it takes a bit more thought to see what the conditions are and when it would be true/false.
if fru in fruits or fru=='1':
March 19th, 2013, 03:59 AM
Well sure, but it’s just as easy to use list concatenation:
Originally Posted by codergeek42
I have no idea where you got that compiler.ast thingy–seems not be present in my Python installations, nor is it documented in docs.python.org!
if fru in fruits + ['1']:
My armada: openSUSE 13.2 (home desktop, home laptop, work desktop), Debian GNU/Linux 7.7.0 (server), OpenELEC 5.0 (HTPC), Android 4.2.1 (tablet)
March 19th, 2013, 04:44 AM
Thanks a lot for your help guys. That was really well elaborated
Gotta get play around with lists for a while
March 23rd, 2013, 03:50 PM
I forgot you could do that with lists...Derp. Thanks.
Originally Posted by SuperOscar
Hmm...that's odd. I did a quick Google search and found it mentioned on some other forums. On my Fedora system, it's part of the core install, so...