How to test multiple variables against a value?AND/OR in Python?Why does checking a variable against multiple values with `OR` only check the first value?If statement for strings in python?Using OR comparisons with IF statementsMultiple 'or' condition in PythonDetecting Vowels vs Consonants In Python“or” conditional in Python troublesif 'a' or 'b' in L, where L is a list (Python)Using IF, AND, OR together with EQUAL operand together in PythonMultiple conditions with if/elif statementsCalling a function of a module by using its name (a string)How do I check whether a file exists without exceptions?How do I return multiple values from a function?Using global variables in a functionHow do I sort a dictionary by value?How to make a chain of function decorators?“Least Astonishment” and the Mutable Default ArgumentHow does Python's super() work with multiple inheritance?Pythonic way to create a long multi-line stringWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

Why no parachutes in the Orion AA2 abort test?

PhD: When to quit and move on?

When is one 'Ready' to make Original Contributions to Mathematics?

Sleepy tired vs physically tired

Boss furious on bad appraisal

What is it called when the tritone is added to a minor scale?

Do intermediate subdomains need to exist?

What instances can be solved today by modern solvers (pure LP)?

Would the Life cleric's Disciple of Life feature supercharge the Regenerate spell?

What is the fundamental difference between catching whales and hunting other animals?

Can a USB hub be used to access a drive from 2 devices?

Is it possible to spoof an IP address to an exact number?

Way to see all encrypted fields in Salesforce?

How would a sea turtle end up on its back?

Is it bad to suddenly introduce another element to your fantasy world a good ways into the story?

Why did Super-VGA offer the 5:4 1280*1024 resolution?

Clear all code blocks

Red and White Squares

What are some bad ways to subvert tropes?

Are "confidant" and "confident" homophones?

Does 5e have an equivalent of the Psychic Paper from Doctor Who?

Taking advantage when the HR forgets to communicate the rules

The Purpose of "Natu"

What is the difference between an "empty interior" and a "hole" in topology?



How to test multiple variables against a value?


AND/OR in Python?Why does checking a variable against multiple values with `OR` only check the first value?If statement for strings in python?Using OR comparisons with IF statementsMultiple 'or' condition in PythonDetecting Vowels vs Consonants In Python“or” conditional in Python troublesif 'a' or 'b' in L, where L is a list (Python)Using IF, AND, OR together with EQUAL operand together in PythonMultiple conditions with if/elif statementsCalling a function of a module by using its name (a string)How do I check whether a file exists without exceptions?How do I return multiple values from a function?Using global variables in a functionHow do I sort a dictionary by value?How to make a chain of function decorators?“Least Astonishment” and the Mutable Default ArgumentHow does Python's super() work with multiple inheritance?Pythonic way to create a long multi-line stringWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








559















I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:



x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
mylist.append("c")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :
mylist.append("e")
if x or y or z == 3 :
mylist.append("f")


which would return a list of



["c", "d", "f"]


Is something like this possible?










share|improve this question



















  • 3





    use 1 in (tuple)

    – Dante
    Dec 5 '17 at 21:49






  • 1





    When you want to evaluate a list of statements in a any/all manner you can use any/all functions. For example: all([1, 2, 3, 4, False]) will return False all([True, 1, 2, 3]) will return True any([False, 0, 0, False]) will return False any([False, 0, True, False]) will return True

    – eddd
    Jun 4 '18 at 16:17












  • I did a summary post based on answers here: medium.com/codervlogger/…

    – Kanan Rahimov
    Feb 12 at 9:30











  • This question is a very popular duplicate target, but I think it's suboptimal for that purpose. Most people try to do something like if x == 0 or 1:, which is of course similar to if x or y == 0:, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't my x == 0 or 1 working?" questions, I would much rather use this question as our canonical duplicate target for these questions.

    – Aran-Fey
    Apr 10 at 10:06











  • Take extra care when comparing to "falsey" values like 0, 0.0 or False. You can easily write wrong code which gives the "right" answer.

    – smci
    Apr 10 at 10:09

















559















I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:



x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
mylist.append("c")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :
mylist.append("e")
if x or y or z == 3 :
mylist.append("f")


which would return a list of



["c", "d", "f"]


Is something like this possible?










share|improve this question



















  • 3





    use 1 in (tuple)

    – Dante
    Dec 5 '17 at 21:49






  • 1





    When you want to evaluate a list of statements in a any/all manner you can use any/all functions. For example: all([1, 2, 3, 4, False]) will return False all([True, 1, 2, 3]) will return True any([False, 0, 0, False]) will return False any([False, 0, True, False]) will return True

    – eddd
    Jun 4 '18 at 16:17












  • I did a summary post based on answers here: medium.com/codervlogger/…

    – Kanan Rahimov
    Feb 12 at 9:30











  • This question is a very popular duplicate target, but I think it's suboptimal for that purpose. Most people try to do something like if x == 0 or 1:, which is of course similar to if x or y == 0:, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't my x == 0 or 1 working?" questions, I would much rather use this question as our canonical duplicate target for these questions.

    – Aran-Fey
    Apr 10 at 10:06











  • Take extra care when comparing to "falsey" values like 0, 0.0 or False. You can easily write wrong code which gives the "right" answer.

    – smci
    Apr 10 at 10:09













559












559








559


109






I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:



x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
mylist.append("c")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :
mylist.append("e")
if x or y or z == 3 :
mylist.append("f")


which would return a list of



["c", "d", "f"]


Is something like this possible?










share|improve this question
















I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:



x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
mylist.append("c")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :
mylist.append("e")
if x or y or z == 3 :
mylist.append("f")


which would return a list of



["c", "d", "f"]


Is something like this possible?







python if-statement comparison match boolean-logic






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 4 at 8:55









Georgy

2,7124 gold badges18 silver badges30 bronze badges




2,7124 gold badges18 silver badges30 bronze badges










asked Feb 27 '13 at 12:26









user1877442user1877442

2,9313 gold badges9 silver badges5 bronze badges




2,9313 gold badges9 silver badges5 bronze badges







  • 3





    use 1 in (tuple)

    – Dante
    Dec 5 '17 at 21:49






  • 1





    When you want to evaluate a list of statements in a any/all manner you can use any/all functions. For example: all([1, 2, 3, 4, False]) will return False all([True, 1, 2, 3]) will return True any([False, 0, 0, False]) will return False any([False, 0, True, False]) will return True

    – eddd
    Jun 4 '18 at 16:17












  • I did a summary post based on answers here: medium.com/codervlogger/…

    – Kanan Rahimov
    Feb 12 at 9:30











  • This question is a very popular duplicate target, but I think it's suboptimal for that purpose. Most people try to do something like if x == 0 or 1:, which is of course similar to if x or y == 0:, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't my x == 0 or 1 working?" questions, I would much rather use this question as our canonical duplicate target for these questions.

    – Aran-Fey
    Apr 10 at 10:06











  • Take extra care when comparing to "falsey" values like 0, 0.0 or False. You can easily write wrong code which gives the "right" answer.

    – smci
    Apr 10 at 10:09












  • 3





    use 1 in (tuple)

    – Dante
    Dec 5 '17 at 21:49






  • 1





    When you want to evaluate a list of statements in a any/all manner you can use any/all functions. For example: all([1, 2, 3, 4, False]) will return False all([True, 1, 2, 3]) will return True any([False, 0, 0, False]) will return False any([False, 0, True, False]) will return True

    – eddd
    Jun 4 '18 at 16:17












  • I did a summary post based on answers here: medium.com/codervlogger/…

    – Kanan Rahimov
    Feb 12 at 9:30











  • This question is a very popular duplicate target, but I think it's suboptimal for that purpose. Most people try to do something like if x == 0 or 1:, which is of course similar to if x or y == 0:, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't my x == 0 or 1 working?" questions, I would much rather use this question as our canonical duplicate target for these questions.

    – Aran-Fey
    Apr 10 at 10:06











  • Take extra care when comparing to "falsey" values like 0, 0.0 or False. You can easily write wrong code which gives the "right" answer.

    – smci
    Apr 10 at 10:09







3




3





use 1 in (tuple)

– Dante
Dec 5 '17 at 21:49





use 1 in (tuple)

– Dante
Dec 5 '17 at 21:49




1




1





When you want to evaluate a list of statements in a any/all manner you can use any/all functions. For example: all([1, 2, 3, 4, False]) will return False all([True, 1, 2, 3]) will return True any([False, 0, 0, False]) will return False any([False, 0, True, False]) will return True

– eddd
Jun 4 '18 at 16:17






When you want to evaluate a list of statements in a any/all manner you can use any/all functions. For example: all([1, 2, 3, 4, False]) will return False all([True, 1, 2, 3]) will return True any([False, 0, 0, False]) will return False any([False, 0, True, False]) will return True

– eddd
Jun 4 '18 at 16:17














I did a summary post based on answers here: medium.com/codervlogger/…

– Kanan Rahimov
Feb 12 at 9:30





I did a summary post based on answers here: medium.com/codervlogger/…

– Kanan Rahimov
Feb 12 at 9:30













This question is a very popular duplicate target, but I think it's suboptimal for that purpose. Most people try to do something like if x == 0 or 1:, which is of course similar to if x or y == 0:, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't my x == 0 or 1 working?" questions, I would much rather use this question as our canonical duplicate target for these questions.

– Aran-Fey
Apr 10 at 10:06





This question is a very popular duplicate target, but I think it's suboptimal for that purpose. Most people try to do something like if x == 0 or 1:, which is of course similar to if x or y == 0:, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't my x == 0 or 1 working?" questions, I would much rather use this question as our canonical duplicate target for these questions.

– Aran-Fey
Apr 10 at 10:06













Take extra care when comparing to "falsey" values like 0, 0.0 or False. You can easily write wrong code which gives the "right" answer.

– smci
Apr 10 at 10:09





Take extra care when comparing to "falsey" values like 0, 0.0 or False. You can easily write wrong code which gives the "right" answer.

– smci
Apr 10 at 10:09












21 Answers
21






active

oldest

votes


















737





+500









You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:



if x == 1 or y == 1 or z == 1:


x and y are otherwise evaluated on their own (False if 0, True otherwise).



You can shorten that using a containment test against a tuple:



if 1 in (x, y, z):


or better still:



if 1 in x, y, z:


using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).



When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.



This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.



However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.



x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).



So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.



The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in 1, 2, 3.






share|improve this answer




















  • 97





    I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

    – SingleNegationElimination
    Oct 24 '13 at 15:27







  • 45





    @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

    – Martijn Pieters
    Oct 24 '13 at 15:29







  • 9





    @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

    – Martijn Pieters
    Oct 24 '13 at 15:37






  • 13





    @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

    – ShadowRanger
    Sep 4 '16 at 0:37






  • 5





    @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

    – Martijn Pieters
    Sep 4 '16 at 7:58


















85














Your problem is more easily addressed with a dictionary structure like:



x = 0
y = 1
z = 3
d = 0: 'c', 1:'d', 2:'e', 3:'f'
mylist = [d[k] for k in [x, y, z]]





share|improve this answer




















  • 18





    Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

    – aragaer
    Oct 24 '13 at 15:39






  • 9





    or map(lambda i: 'cdef'[i], [x, y, z])

    – dansalmo
    May 8 '14 at 14:36






  • 3





    @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

    – dansalmo
    Jul 24 '18 at 21:05






  • 1





    Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

    – LoneWanderer
    Mar 10 at 18:57


















57














As stated by Martijn Pieters, the correct, and fastest, format is:



if 1 in x, y, z:


Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True or False. Such as:



if 0 in x, y, z:
mylist.append("c")
if 1 in x, y, z:
mylist.append("d")
if 2 in x, y, z:
mylist.append("e")
...


This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:



num_to_letters = 0: "c", 1: "d", 2: "e", 3: "f"
for number in num_to_letters:
if number in x, y, z:
mylist.append(num_to_letters[number])





share|improve this answer
































    42














    The direct way to write x or y or z == 0 is



    if any(map((lambda value: value == 0), (x,y,z))):
    pass # write your logic.


    But I dont think, you like it. :)
    And this way is ugly.



    The other way (a better) is:



    0 in (x, y, z)


    BTW lots of ifs could be written as something like this



    my_cases = 
    0: Mylist.append("c"),
    1: Mylist.append("d")
    # ..


    for key in my_cases:
    if key in (x,y,z):
    my_cases[key]()
    break





    share|improve this answer




















    • 6





      In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

      – SethMMorton
      Feb 8 '14 at 20:57












    • the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

      – Mahmoud Elshahat
      Apr 7 at 1:41


















    29














    If you ARE very very lazy, you can put the values inside an array. Such as



    list = []
    list.append(x)
    list.append(y)
    list.append(z)
    nums = [add numbers here]
    letters = [add corresponding letters here]
    for index in range(len(nums)):
    for obj in list:
    if obj == num[index]:
    MyList.append(letters[index])
    break


    You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)



    One more thing, your



    if x or y or z == 0:


    will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)



    if b


    the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is



    if bool(b)


    Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))



    Another lazy way I found is :



    if any([x==0, y==0, z==0])





    share|improve this answer
































      27














      To check if a value is contained within a set of variables you can use the inbuilt modules itertools and operator.



      For example:



      Imports:



      from itertools import repeat
      from operator import contains


      Declare variables:



      x = 0
      y = 1
      z = 3


      Create mapping of values (in the order you want to check):



      check_values = (0, 1, 3)


      Use itertools to allow repetition of the variables:



      check_vars = repeat((x, y, z))


      Finally, use the map function to create an iterator:



      checker = map(contains, check_vars, check_values)


      Then, when checking for the values (in the original order), use next():



      if next(checker) # Checks for 0
      # Do something
      pass
      elif next(checker) # Checks for 1
      # Do something
      pass


      etc...



      This has an advantage over the lambda x: x in (variables) because operator is an inbuilt module and is faster and more efficient than using lambda which has to create a custom in-place function.



      Another option for checking if there is a non-zero (or False) value in a list:



      not (x and y and z)


      Equivalent:



      not all((x, y, z))





      share|improve this answer




















      • 1





        This doesn't answer the OP's question. It only covers the first case in the provided example.

        – wallacer
        Jun 4 '14 at 17:39


















      25














      I think this will handle it better:



      my_dict = 0: "c", 1: "d", 2: "e", 3: "f"

      def validate(x, y, z):
      for ele in [x, y, z]:
      if ele in my_dict.keys():
      return my_dict[ele]


      Output:



      print validate(0, 8, 9)
      c
      print validate(9, 8, 9)
      None
      print validate(9, 8, 2)
      e





      share|improve this answer
































        25














        Set is the good approach here, because it orders the variables, what seems to be your goal here. z,y,x is 0,1,3 whatever the order of the parameters.



        >>> ["cdef"[i] for i in z,x,y]
        ['c', 'd', 'f']


        This way, the whole solution is O(n).






        share|improve this answer




















        • 4





          You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

          – Raniz
          Jun 10 '15 at 4:19


















        25














        If you want to use if, else statements following is another solution:



        myList = []
        aList = [0, 1, 3]

        for l in aList:
        if l==0: myList.append('c')
        elif l==1: myList.append('d')
        elif l==2: myList.append('e')
        elif l==3: myList.append('f')

        print(myList)





        share|improve this answer
































          25














          All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in x,y,z solution put forward by Martijn Pieters.

          What they ignore is the broader implication of the question:
          How do I test one variable against multiple values?

          The solution provided will not work for partial hits if using strings for example:

          Test if the string "Wild" is in multiple values



          >>> x = "Wild things"
          >>> y = "throttle it back"
          >>> z = "in the beginning"
          >>> if "Wild" in x, y, z: print (True)
          ...


          or



          >>> x = "Wild things"
          >>> y = "throttle it back"
          >>> z = "in the beginning"
          >>> if "Wild" in [x, y, z]: print (True)
          ...


          for this scenario it's easiest to convert to a string



          >>> [x, y, z]
          ['Wild things', 'throttle it back', 'in the beginning']
          >>> x, y, z
          'in the beginning', 'throttle it back', 'Wild things'
          >>>

          >>> if "Wild" in str([x, y, z]): print (True)
          ...
          True
          >>> if "Wild" in str(x, y, z): print (True)
          ...
          True


          It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:



          >>> x=['Wild things', 'throttle it back', 'in the beginning']
          >>> if "rot" in str(x): print(True)
          ...
          True


          the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.

          The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.






          share|improve this answer
































            22














            d = 0:'c', 1:'d', 2:'e', 3: 'f'
            x, y, z = (0, 1, 3)
            print [v for (k,v) in d.items() if x==k or y==k or z==k]





            share|improve this answer
































              22














              This code may be helpful



              L =x, y, z
              T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
              List2=[]
              for t in T :
              if t[0] in L :
              List2.append(t[1])
              break;





              share|improve this answer






























                7














                One line solution:



                mylist = [0: 'c', 1: 'd', 2: 'e', 3: 'f'[i] for i in [0, 1, 2, 3] if i in (x, y, z)]


                Or:



                mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]





                share|improve this answer






























                  6














                  You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.



                  mydict = 0:"c", 1:"d", 2:"e", 3:"f"
                  mylist= []

                  num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

                  for i in range(num_var):
                  ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
                  globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
                  mylist += mydict[globals()['var'+str('i').zfill(3)]]

                  print mylist
                  >>> ['c', 'd', 'f']





                  share|improve this answer






























                    5














                    Maybe you need direct formula for output bits set.



                    x=0 or y=0 or z=0 is equivalent to x*y*z = 0

                    x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0

                    x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0


                    Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000



                    Relation of isc (is 'c'):



                    if xyz=0 then isc=1 else isc=0


                    Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315



                    [c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))



                    [d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))



                    ...



                    Connect these formulas by following logic:



                    • logic and is the sum of squares of equations

                    • logic or is the product of equations

                    and you'll have a total equation
                    express sum and you have total formula of sum



                    then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f



                    After this you may form predefined array where index of string elements would correspond to ready string.



                    array[sum] gives you the string.






                    share|improve this answer
































                      4














                      It can be done easily as



                      for value in [var1,var2,var3]:
                      li.append("targetValue")





                      share|improve this answer






























                        3














                        The most mnemonic way of representing your pseudo-code in Python would be:



                        x = 0
                        y = 1
                        z = 3
                        mylist = []

                        if any(v == 0 for v in (x, y, z)):
                        mylist.append("c")
                        if any(v == 1 for v in (x, y, z)):
                        mylist.append("d")
                        if any(v == 2 for v in (x, y, z)):
                        mylist.append("e")
                        if any(v == 3 for v in (x, y, z)):
                        mylist.append("f")





                        share|improve this answer























                        • This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                          – imposeren
                          May 4 at 4:47


















                        3














                        Looks like you're building some kind of Caesar cipher.



                        A much more generalized approach is this:



                        input_values = (0, 1, 3)
                        origo = ord('c')
                        [chr(val + origo) for val in inputs]


                        outputs



                        ['c', 'd', 'f']


                        Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.



                        If this is what you want, the final line can be changed to:



                        sorted([chr(val + origo) for val in inputs])





                        share|improve this answer






























                          3














                          To test multiple variables with one single value: if 1 in a,b,c:



                          To test multiple values with one variable: if a in 1, 2, 3:






                          share|improve this answer






























                            1














                            You can use dictionary :



                            x = 0
                            y = 1
                            z = 3
                            list=[]
                            dict = 0: 'c', 1: 'd', 2: 'e', 3: 'f'
                            if x in dict:
                            list.append(dict[x])
                            else:
                            pass

                            if y in dict:
                            list.append(dict[y])
                            else:
                            pass
                            if z in dict:
                            list.append(dict[z])
                            else:
                            pass

                            print list





                            share|improve this answer























                            • This may append same more then once this. Set?

                              – Sergei
                              Feb 19 at 4:49


















                            0














                            This will help you.



                            def test_fun(val):
                            x = 0
                            y = 1
                            z = 2
                            myList = []
                            if val in (x, y, z) and val == 0:
                            myList.append("C")
                            if val in (x, y, z) and val == 1:
                            myList.append("D")
                            if val in (x, y, z) and val == 2:
                            myList.append("E")

                            test_fun(2);





                            share|improve this answer

























                              protected by Martijn Pieters Mar 8 '15 at 1:18



                              Thank you for your interest in this question.
                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                              Would you like to answer one of these unanswered questions instead?














                              21 Answers
                              21






                              active

                              oldest

                              votes








                              21 Answers
                              21






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes









                              737





                              +500









                              You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:



                              if x == 1 or y == 1 or z == 1:


                              x and y are otherwise evaluated on their own (False if 0, True otherwise).



                              You can shorten that using a containment test against a tuple:



                              if 1 in (x, y, z):


                              or better still:



                              if 1 in x, y, z:


                              using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).



                              When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.



                              This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.



                              However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.



                              x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).



                              So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.



                              The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in 1, 2, 3.






                              share|improve this answer




















                              • 97





                                I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

                                – SingleNegationElimination
                                Oct 24 '13 at 15:27







                              • 45





                                @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

                                – Martijn Pieters
                                Oct 24 '13 at 15:29







                              • 9





                                @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

                                – Martijn Pieters
                                Oct 24 '13 at 15:37






                              • 13





                                @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

                                – ShadowRanger
                                Sep 4 '16 at 0:37






                              • 5





                                @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

                                – Martijn Pieters
                                Sep 4 '16 at 7:58















                              737





                              +500









                              You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:



                              if x == 1 or y == 1 or z == 1:


                              x and y are otherwise evaluated on their own (False if 0, True otherwise).



                              You can shorten that using a containment test against a tuple:



                              if 1 in (x, y, z):


                              or better still:



                              if 1 in x, y, z:


                              using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).



                              When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.



                              This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.



                              However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.



                              x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).



                              So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.



                              The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in 1, 2, 3.






                              share|improve this answer




















                              • 97





                                I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

                                – SingleNegationElimination
                                Oct 24 '13 at 15:27







                              • 45





                                @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

                                – Martijn Pieters
                                Oct 24 '13 at 15:29







                              • 9





                                @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

                                – Martijn Pieters
                                Oct 24 '13 at 15:37






                              • 13





                                @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

                                – ShadowRanger
                                Sep 4 '16 at 0:37






                              • 5





                                @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

                                – Martijn Pieters
                                Sep 4 '16 at 7:58













                              737





                              +500







                              737





                              +500



                              737




                              +500





                              You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:



                              if x == 1 or y == 1 or z == 1:


                              x and y are otherwise evaluated on their own (False if 0, True otherwise).



                              You can shorten that using a containment test against a tuple:



                              if 1 in (x, y, z):


                              or better still:



                              if 1 in x, y, z:


                              using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).



                              When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.



                              This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.



                              However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.



                              x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).



                              So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.



                              The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in 1, 2, 3.






                              share|improve this answer















                              You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:



                              if x == 1 or y == 1 or z == 1:


                              x and y are otherwise evaluated on their own (False if 0, True otherwise).



                              You can shorten that using a containment test against a tuple:



                              if 1 in (x, y, z):


                              or better still:



                              if 1 in x, y, z:


                              using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).



                              When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.



                              This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.



                              However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.



                              x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).



                              So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.



                              The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in 1, 2, 3.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 12 '18 at 19:56

























                              answered Feb 27 '13 at 12:27









                              Martijn PietersMartijn Pieters

                              744k157 gold badges2676 silver badges2410 bronze badges




                              744k157 gold badges2676 silver badges2410 bronze badges







                              • 97





                                I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

                                – SingleNegationElimination
                                Oct 24 '13 at 15:27







                              • 45





                                @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

                                – Martijn Pieters
                                Oct 24 '13 at 15:29







                              • 9





                                @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

                                – Martijn Pieters
                                Oct 24 '13 at 15:37






                              • 13





                                @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

                                – ShadowRanger
                                Sep 4 '16 at 0:37






                              • 5





                                @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

                                – Martijn Pieters
                                Sep 4 '16 at 7:58












                              • 97





                                I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

                                – SingleNegationElimination
                                Oct 24 '13 at 15:27







                              • 45





                                @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

                                – Martijn Pieters
                                Oct 24 '13 at 15:29







                              • 9





                                @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

                                – Martijn Pieters
                                Oct 24 '13 at 15:37






                              • 13





                                @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

                                – ShadowRanger
                                Sep 4 '16 at 0:37






                              • 5





                                @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

                                – Martijn Pieters
                                Sep 4 '16 at 7:58







                              97




                              97





                              I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

                              – SingleNegationElimination
                              Oct 24 '13 at 15:27






                              I wouldn't be so quick to go for the set version. Tuple's are very cheap to create and iterate over. On my machine at least, tuples are faster than sets so long as the size of the tuple is around 4-8 elements. If you have to scan more than that, use a set, but if you are looking for an item out of 2-4 possibilities, a tuple is still faster! If you can arrange for the most likely case to be first in the tuple, the win is even bigger: (my test: timeit.timeit('0 in seq'.format(seq=tuple(range(9, -1, -1)))))

                              – SingleNegationElimination
                              Oct 24 '13 at 15:27





                              45




                              45





                              @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

                              – Martijn Pieters
                              Oct 24 '13 at 15:29






                              @dequestarmappartialsetattr: In Python 3.3 and up, the set is stored as a constant, bypassing the creation time altogether, eliminating the creation time. Tuples can be cheap to create as Python caches a bundle of them to avoid memory churn, making that the biggest difference with sets here.

                              – Martijn Pieters
                              Oct 24 '13 at 15:29





                              9




                              9





                              @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

                              – Martijn Pieters
                              Oct 24 '13 at 15:37





                              @dequestarmappartialsetattr: If you time just the membership test, for integers sets and tuples are equally fast for the ideal scenario; matching the first element. After that tuples lose out to sets.

                              – Martijn Pieters
                              Oct 24 '13 at 15:37




                              13




                              13





                              @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

                              – ShadowRanger
                              Sep 4 '16 at 0:37





                              @MartijnPieters: Using the set literal notation for this test isn't a savings unless the contents of the set literal are also literals, right? if 1 in x, y, z: can't cache the set, because x, y and z could change, so either solution needs to build a tuple or set from scratch, and I suspect whatever lookup savings you might get when checking for membership would be swamped by greater set creation time.

                              – ShadowRanger
                              Sep 4 '16 at 0:37




                              5




                              5





                              @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

                              – Martijn Pieters
                              Sep 4 '16 at 7:58





                              @ShadowRanger: yes, peephole optimisation (be it for in [...] or in ...) only works if the contents of the list or set are immutable literals too.

                              – Martijn Pieters
                              Sep 4 '16 at 7:58













                              85














                              Your problem is more easily addressed with a dictionary structure like:



                              x = 0
                              y = 1
                              z = 3
                              d = 0: 'c', 1:'d', 2:'e', 3:'f'
                              mylist = [d[k] for k in [x, y, z]]





                              share|improve this answer




















                              • 18





                                Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

                                – aragaer
                                Oct 24 '13 at 15:39






                              • 9





                                or map(lambda i: 'cdef'[i], [x, y, z])

                                – dansalmo
                                May 8 '14 at 14:36






                              • 3





                                @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

                                – dansalmo
                                Jul 24 '18 at 21:05






                              • 1





                                Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

                                – LoneWanderer
                                Mar 10 at 18:57















                              85














                              Your problem is more easily addressed with a dictionary structure like:



                              x = 0
                              y = 1
                              z = 3
                              d = 0: 'c', 1:'d', 2:'e', 3:'f'
                              mylist = [d[k] for k in [x, y, z]]





                              share|improve this answer




















                              • 18





                                Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

                                – aragaer
                                Oct 24 '13 at 15:39






                              • 9





                                or map(lambda i: 'cdef'[i], [x, y, z])

                                – dansalmo
                                May 8 '14 at 14:36






                              • 3





                                @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

                                – dansalmo
                                Jul 24 '18 at 21:05






                              • 1





                                Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

                                – LoneWanderer
                                Mar 10 at 18:57













                              85












                              85








                              85







                              Your problem is more easily addressed with a dictionary structure like:



                              x = 0
                              y = 1
                              z = 3
                              d = 0: 'c', 1:'d', 2:'e', 3:'f'
                              mylist = [d[k] for k in [x, y, z]]





                              share|improve this answer















                              Your problem is more easily addressed with a dictionary structure like:



                              x = 0
                              y = 1
                              z = 3
                              d = 0: 'c', 1:'d', 2:'e', 3:'f'
                              mylist = [d[k] for k in [x, y, z]]






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 25 '17 at 14:45









                              River

                              5,8168 gold badges39 silver badges56 bronze badges




                              5,8168 gold badges39 silver badges56 bronze badges










                              answered Jul 11 '13 at 21:56









                              dansalmodansalmo

                              8,6394 gold badges43 silver badges46 bronze badges




                              8,6394 gold badges43 silver badges46 bronze badges







                              • 18





                                Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

                                – aragaer
                                Oct 24 '13 at 15:39






                              • 9





                                or map(lambda i: 'cdef'[i], [x, y, z])

                                – dansalmo
                                May 8 '14 at 14:36






                              • 3





                                @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

                                – dansalmo
                                Jul 24 '18 at 21:05






                              • 1





                                Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

                                – LoneWanderer
                                Mar 10 at 18:57












                              • 18





                                Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

                                – aragaer
                                Oct 24 '13 at 15:39






                              • 9





                                or map(lambda i: 'cdef'[i], [x, y, z])

                                – dansalmo
                                May 8 '14 at 14:36






                              • 3





                                @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

                                – dansalmo
                                Jul 24 '18 at 21:05






                              • 1





                                Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

                                – LoneWanderer
                                Mar 10 at 18:57







                              18




                              18





                              Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

                              – aragaer
                              Oct 24 '13 at 15:39





                              Or even d = "cdef" which leads to MyList = ["cdef"[k] for k in [x, y, z]]

                              – aragaer
                              Oct 24 '13 at 15:39




                              9




                              9





                              or map(lambda i: 'cdef'[i], [x, y, z])

                              – dansalmo
                              May 8 '14 at 14:36





                              or map(lambda i: 'cdef'[i], [x, y, z])

                              – dansalmo
                              May 8 '14 at 14:36




                              3




                              3





                              @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

                              – dansalmo
                              Jul 24 '18 at 21:05





                              @MJM the output order is not determined by the dict, it is determined by the order of the list [x, y, z]

                              – dansalmo
                              Jul 24 '18 at 21:05




                              1




                              1





                              Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

                              – LoneWanderer
                              Mar 10 at 18:57





                              Aside from the list comprehension which I'm not yet fully accustomed to, most of us had the same reflex: build that dict !

                              – LoneWanderer
                              Mar 10 at 18:57











                              57














                              As stated by Martijn Pieters, the correct, and fastest, format is:



                              if 1 in x, y, z:


                              Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True or False. Such as:



                              if 0 in x, y, z:
                              mylist.append("c")
                              if 1 in x, y, z:
                              mylist.append("d")
                              if 2 in x, y, z:
                              mylist.append("e")
                              ...


                              This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:



                              num_to_letters = 0: "c", 1: "d", 2: "e", 3: "f"
                              for number in num_to_letters:
                              if number in x, y, z:
                              mylist.append(num_to_letters[number])





                              share|improve this answer





























                                57














                                As stated by Martijn Pieters, the correct, and fastest, format is:



                                if 1 in x, y, z:


                                Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True or False. Such as:



                                if 0 in x, y, z:
                                mylist.append("c")
                                if 1 in x, y, z:
                                mylist.append("d")
                                if 2 in x, y, z:
                                mylist.append("e")
                                ...


                                This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:



                                num_to_letters = 0: "c", 1: "d", 2: "e", 3: "f"
                                for number in num_to_letters:
                                if number in x, y, z:
                                mylist.append(num_to_letters[number])





                                share|improve this answer



























                                  57












                                  57








                                  57







                                  As stated by Martijn Pieters, the correct, and fastest, format is:



                                  if 1 in x, y, z:


                                  Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True or False. Such as:



                                  if 0 in x, y, z:
                                  mylist.append("c")
                                  if 1 in x, y, z:
                                  mylist.append("d")
                                  if 2 in x, y, z:
                                  mylist.append("e")
                                  ...


                                  This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:



                                  num_to_letters = 0: "c", 1: "d", 2: "e", 3: "f"
                                  for number in num_to_letters:
                                  if number in x, y, z:
                                  mylist.append(num_to_letters[number])





                                  share|improve this answer















                                  As stated by Martijn Pieters, the correct, and fastest, format is:



                                  if 1 in x, y, z:


                                  Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True or False. Such as:



                                  if 0 in x, y, z:
                                  mylist.append("c")
                                  if 1 in x, y, z:
                                  mylist.append("d")
                                  if 2 in x, y, z:
                                  mylist.append("e")
                                  ...


                                  This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:



                                  num_to_letters = 0: "c", 1: "d", 2: "e", 3: "f"
                                  for number in num_to_letters:
                                  if number in x, y, z:
                                  mylist.append(num_to_letters[number])






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited May 7 at 9:30









                                  Georgy

                                  2,7124 gold badges18 silver badges30 bronze badges




                                  2,7124 gold badges18 silver badges30 bronze badges










                                  answered Aug 19 '15 at 2:34









                                  ThatGuyRussellThatGuyRussell

                                  1,0186 silver badges17 bronze badges




                                  1,0186 silver badges17 bronze badges





















                                      42














                                      The direct way to write x or y or z == 0 is



                                      if any(map((lambda value: value == 0), (x,y,z))):
                                      pass # write your logic.


                                      But I dont think, you like it. :)
                                      And this way is ugly.



                                      The other way (a better) is:



                                      0 in (x, y, z)


                                      BTW lots of ifs could be written as something like this



                                      my_cases = 
                                      0: Mylist.append("c"),
                                      1: Mylist.append("d")
                                      # ..


                                      for key in my_cases:
                                      if key in (x,y,z):
                                      my_cases[key]()
                                      break





                                      share|improve this answer




















                                      • 6





                                        In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

                                        – SethMMorton
                                        Feb 8 '14 at 20:57












                                      • the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

                                        – Mahmoud Elshahat
                                        Apr 7 at 1:41















                                      42














                                      The direct way to write x or y or z == 0 is



                                      if any(map((lambda value: value == 0), (x,y,z))):
                                      pass # write your logic.


                                      But I dont think, you like it. :)
                                      And this way is ugly.



                                      The other way (a better) is:



                                      0 in (x, y, z)


                                      BTW lots of ifs could be written as something like this



                                      my_cases = 
                                      0: Mylist.append("c"),
                                      1: Mylist.append("d")
                                      # ..


                                      for key in my_cases:
                                      if key in (x,y,z):
                                      my_cases[key]()
                                      break





                                      share|improve this answer




















                                      • 6





                                        In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

                                        – SethMMorton
                                        Feb 8 '14 at 20:57












                                      • the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

                                        – Mahmoud Elshahat
                                        Apr 7 at 1:41













                                      42












                                      42








                                      42







                                      The direct way to write x or y or z == 0 is



                                      if any(map((lambda value: value == 0), (x,y,z))):
                                      pass # write your logic.


                                      But I dont think, you like it. :)
                                      And this way is ugly.



                                      The other way (a better) is:



                                      0 in (x, y, z)


                                      BTW lots of ifs could be written as something like this



                                      my_cases = 
                                      0: Mylist.append("c"),
                                      1: Mylist.append("d")
                                      # ..


                                      for key in my_cases:
                                      if key in (x,y,z):
                                      my_cases[key]()
                                      break





                                      share|improve this answer















                                      The direct way to write x or y or z == 0 is



                                      if any(map((lambda value: value == 0), (x,y,z))):
                                      pass # write your logic.


                                      But I dont think, you like it. :)
                                      And this way is ugly.



                                      The other way (a better) is:



                                      0 in (x, y, z)


                                      BTW lots of ifs could be written as something like this



                                      my_cases = 
                                      0: Mylist.append("c"),
                                      1: Mylist.append("d")
                                      # ..


                                      for key in my_cases:
                                      if key in (x,y,z):
                                      my_cases[key]()
                                      break






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jul 11 '13 at 21:24

























                                      answered Jul 11 '13 at 21:16









                                      akaRemakaRem

                                      3,4173 gold badges23 silver badges36 bronze badges




                                      3,4173 gold badges23 silver badges36 bronze badges







                                      • 6





                                        In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

                                        – SethMMorton
                                        Feb 8 '14 at 20:57












                                      • the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

                                        – Mahmoud Elshahat
                                        Apr 7 at 1:41












                                      • 6





                                        In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

                                        – SethMMorton
                                        Feb 8 '14 at 20:57












                                      • the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

                                        – Mahmoud Elshahat
                                        Apr 7 at 1:41







                                      6




                                      6





                                      In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

                                      – SethMMorton
                                      Feb 8 '14 at 20:57






                                      In your example of the dict instead of a key, you will get errors because the return value of .append is None, and calling None gives an AttributeError. In general I agree with this method, though.

                                      – SethMMorton
                                      Feb 8 '14 at 20:57














                                      the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

                                      – Mahmoud Elshahat
                                      Apr 7 at 1:41





                                      the dict instead of a key is wrong, you will get Mylist=['c', 'd'] when the dictionary get initialized even if you commented out "for..loop" part

                                      – Mahmoud Elshahat
                                      Apr 7 at 1:41











                                      29














                                      If you ARE very very lazy, you can put the values inside an array. Such as



                                      list = []
                                      list.append(x)
                                      list.append(y)
                                      list.append(z)
                                      nums = [add numbers here]
                                      letters = [add corresponding letters here]
                                      for index in range(len(nums)):
                                      for obj in list:
                                      if obj == num[index]:
                                      MyList.append(letters[index])
                                      break


                                      You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)



                                      One more thing, your



                                      if x or y or z == 0:


                                      will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)



                                      if b


                                      the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is



                                      if bool(b)


                                      Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))



                                      Another lazy way I found is :



                                      if any([x==0, y==0, z==0])





                                      share|improve this answer





























                                        29














                                        If you ARE very very lazy, you can put the values inside an array. Such as



                                        list = []
                                        list.append(x)
                                        list.append(y)
                                        list.append(z)
                                        nums = [add numbers here]
                                        letters = [add corresponding letters here]
                                        for index in range(len(nums)):
                                        for obj in list:
                                        if obj == num[index]:
                                        MyList.append(letters[index])
                                        break


                                        You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)



                                        One more thing, your



                                        if x or y or z == 0:


                                        will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)



                                        if b


                                        the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is



                                        if bool(b)


                                        Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))



                                        Another lazy way I found is :



                                        if any([x==0, y==0, z==0])





                                        share|improve this answer



























                                          29












                                          29








                                          29







                                          If you ARE very very lazy, you can put the values inside an array. Such as



                                          list = []
                                          list.append(x)
                                          list.append(y)
                                          list.append(z)
                                          nums = [add numbers here]
                                          letters = [add corresponding letters here]
                                          for index in range(len(nums)):
                                          for obj in list:
                                          if obj == num[index]:
                                          MyList.append(letters[index])
                                          break


                                          You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)



                                          One more thing, your



                                          if x or y or z == 0:


                                          will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)



                                          if b


                                          the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is



                                          if bool(b)


                                          Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))



                                          Another lazy way I found is :



                                          if any([x==0, y==0, z==0])





                                          share|improve this answer















                                          If you ARE very very lazy, you can put the values inside an array. Such as



                                          list = []
                                          list.append(x)
                                          list.append(y)
                                          list.append(z)
                                          nums = [add numbers here]
                                          letters = [add corresponding letters here]
                                          for index in range(len(nums)):
                                          for obj in list:
                                          if obj == num[index]:
                                          MyList.append(letters[index])
                                          break


                                          You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)



                                          One more thing, your



                                          if x or y or z == 0:


                                          will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)



                                          if b


                                          the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is



                                          if bool(b)


                                          Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))



                                          Another lazy way I found is :



                                          if any([x==0, y==0, z==0])






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Aug 13 '15 at 18:06

























                                          answered May 25 '15 at 3:53









                                          ytpillaiytpillai

                                          2,44219 silver badges37 bronze badges




                                          2,44219 silver badges37 bronze badges





















                                              27














                                              To check if a value is contained within a set of variables you can use the inbuilt modules itertools and operator.



                                              For example:



                                              Imports:



                                              from itertools import repeat
                                              from operator import contains


                                              Declare variables:



                                              x = 0
                                              y = 1
                                              z = 3


                                              Create mapping of values (in the order you want to check):



                                              check_values = (0, 1, 3)


                                              Use itertools to allow repetition of the variables:



                                              check_vars = repeat((x, y, z))


                                              Finally, use the map function to create an iterator:



                                              checker = map(contains, check_vars, check_values)


                                              Then, when checking for the values (in the original order), use next():



                                              if next(checker) # Checks for 0
                                              # Do something
                                              pass
                                              elif next(checker) # Checks for 1
                                              # Do something
                                              pass


                                              etc...



                                              This has an advantage over the lambda x: x in (variables) because operator is an inbuilt module and is faster and more efficient than using lambda which has to create a custom in-place function.



                                              Another option for checking if there is a non-zero (or False) value in a list:



                                              not (x and y and z)


                                              Equivalent:



                                              not all((x, y, z))





                                              share|improve this answer




















                                              • 1





                                                This doesn't answer the OP's question. It only covers the first case in the provided example.

                                                – wallacer
                                                Jun 4 '14 at 17:39















                                              27














                                              To check if a value is contained within a set of variables you can use the inbuilt modules itertools and operator.



                                              For example:



                                              Imports:



                                              from itertools import repeat
                                              from operator import contains


                                              Declare variables:



                                              x = 0
                                              y = 1
                                              z = 3


                                              Create mapping of values (in the order you want to check):



                                              check_values = (0, 1, 3)


                                              Use itertools to allow repetition of the variables:



                                              check_vars = repeat((x, y, z))


                                              Finally, use the map function to create an iterator:



                                              checker = map(contains, check_vars, check_values)


                                              Then, when checking for the values (in the original order), use next():



                                              if next(checker) # Checks for 0
                                              # Do something
                                              pass
                                              elif next(checker) # Checks for 1
                                              # Do something
                                              pass


                                              etc...



                                              This has an advantage over the lambda x: x in (variables) because operator is an inbuilt module and is faster and more efficient than using lambda which has to create a custom in-place function.



                                              Another option for checking if there is a non-zero (or False) value in a list:



                                              not (x and y and z)


                                              Equivalent:



                                              not all((x, y, z))





                                              share|improve this answer




















                                              • 1





                                                This doesn't answer the OP's question. It only covers the first case in the provided example.

                                                – wallacer
                                                Jun 4 '14 at 17:39













                                              27












                                              27








                                              27







                                              To check if a value is contained within a set of variables you can use the inbuilt modules itertools and operator.



                                              For example:



                                              Imports:



                                              from itertools import repeat
                                              from operator import contains


                                              Declare variables:



                                              x = 0
                                              y = 1
                                              z = 3


                                              Create mapping of values (in the order you want to check):



                                              check_values = (0, 1, 3)


                                              Use itertools to allow repetition of the variables:



                                              check_vars = repeat((x, y, z))


                                              Finally, use the map function to create an iterator:



                                              checker = map(contains, check_vars, check_values)


                                              Then, when checking for the values (in the original order), use next():



                                              if next(checker) # Checks for 0
                                              # Do something
                                              pass
                                              elif next(checker) # Checks for 1
                                              # Do something
                                              pass


                                              etc...



                                              This has an advantage over the lambda x: x in (variables) because operator is an inbuilt module and is faster and more efficient than using lambda which has to create a custom in-place function.



                                              Another option for checking if there is a non-zero (or False) value in a list:



                                              not (x and y and z)


                                              Equivalent:



                                              not all((x, y, z))





                                              share|improve this answer















                                              To check if a value is contained within a set of variables you can use the inbuilt modules itertools and operator.



                                              For example:



                                              Imports:



                                              from itertools import repeat
                                              from operator import contains


                                              Declare variables:



                                              x = 0
                                              y = 1
                                              z = 3


                                              Create mapping of values (in the order you want to check):



                                              check_values = (0, 1, 3)


                                              Use itertools to allow repetition of the variables:



                                              check_vars = repeat((x, y, z))


                                              Finally, use the map function to create an iterator:



                                              checker = map(contains, check_vars, check_values)


                                              Then, when checking for the values (in the original order), use next():



                                              if next(checker) # Checks for 0
                                              # Do something
                                              pass
                                              elif next(checker) # Checks for 1
                                              # Do something
                                              pass


                                              etc...



                                              This has an advantage over the lambda x: x in (variables) because operator is an inbuilt module and is faster and more efficient than using lambda which has to create a custom in-place function.



                                              Another option for checking if there is a non-zero (or False) value in a list:



                                              not (x and y and z)


                                              Equivalent:



                                              not all((x, y, z))






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jun 5 '14 at 11:31

























                                              answered Jun 4 '14 at 17:09









                                              GuiltyDolphinGuiltyDolphin

                                              6501 gold badge7 silver badges10 bronze badges




                                              6501 gold badge7 silver badges10 bronze badges







                                              • 1





                                                This doesn't answer the OP's question. It only covers the first case in the provided example.

                                                – wallacer
                                                Jun 4 '14 at 17:39












                                              • 1





                                                This doesn't answer the OP's question. It only covers the first case in the provided example.

                                                – wallacer
                                                Jun 4 '14 at 17:39







                                              1




                                              1





                                              This doesn't answer the OP's question. It only covers the first case in the provided example.

                                              – wallacer
                                              Jun 4 '14 at 17:39





                                              This doesn't answer the OP's question. It only covers the first case in the provided example.

                                              – wallacer
                                              Jun 4 '14 at 17:39











                                              25














                                              I think this will handle it better:



                                              my_dict = 0: "c", 1: "d", 2: "e", 3: "f"

                                              def validate(x, y, z):
                                              for ele in [x, y, z]:
                                              if ele in my_dict.keys():
                                              return my_dict[ele]


                                              Output:



                                              print validate(0, 8, 9)
                                              c
                                              print validate(9, 8, 9)
                                              None
                                              print validate(9, 8, 2)
                                              e





                                              share|improve this answer





























                                                25














                                                I think this will handle it better:



                                                my_dict = 0: "c", 1: "d", 2: "e", 3: "f"

                                                def validate(x, y, z):
                                                for ele in [x, y, z]:
                                                if ele in my_dict.keys():
                                                return my_dict[ele]


                                                Output:



                                                print validate(0, 8, 9)
                                                c
                                                print validate(9, 8, 9)
                                                None
                                                print validate(9, 8, 2)
                                                e





                                                share|improve this answer



























                                                  25












                                                  25








                                                  25







                                                  I think this will handle it better:



                                                  my_dict = 0: "c", 1: "d", 2: "e", 3: "f"

                                                  def validate(x, y, z):
                                                  for ele in [x, y, z]:
                                                  if ele in my_dict.keys():
                                                  return my_dict[ele]


                                                  Output:



                                                  print validate(0, 8, 9)
                                                  c
                                                  print validate(9, 8, 9)
                                                  None
                                                  print validate(9, 8, 2)
                                                  e





                                                  share|improve this answer















                                                  I think this will handle it better:



                                                  my_dict = 0: "c", 1: "d", 2: "e", 3: "f"

                                                  def validate(x, y, z):
                                                  for ele in [x, y, z]:
                                                  if ele in my_dict.keys():
                                                  return my_dict[ele]


                                                  Output:



                                                  print validate(0, 8, 9)
                                                  c
                                                  print validate(9, 8, 9)
                                                  None
                                                  print validate(9, 8, 2)
                                                  e






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Feb 10 '15 at 14:58









                                                  shuttle87

                                                  11.5k6 gold badges61 silver badges100 bronze badges




                                                  11.5k6 gold badges61 silver badges100 bronze badges










                                                  answered Jan 13 '15 at 12:10









                                                  Bhargav BodaBhargav Boda

                                                  2613 silver badges3 bronze badges




                                                  2613 silver badges3 bronze badges





















                                                      25














                                                      Set is the good approach here, because it orders the variables, what seems to be your goal here. z,y,x is 0,1,3 whatever the order of the parameters.



                                                      >>> ["cdef"[i] for i in z,x,y]
                                                      ['c', 'd', 'f']


                                                      This way, the whole solution is O(n).






                                                      share|improve this answer




















                                                      • 4





                                                        You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

                                                        – Raniz
                                                        Jun 10 '15 at 4:19















                                                      25














                                                      Set is the good approach here, because it orders the variables, what seems to be your goal here. z,y,x is 0,1,3 whatever the order of the parameters.



                                                      >>> ["cdef"[i] for i in z,x,y]
                                                      ['c', 'd', 'f']


                                                      This way, the whole solution is O(n).






                                                      share|improve this answer




















                                                      • 4





                                                        You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

                                                        – Raniz
                                                        Jun 10 '15 at 4:19













                                                      25












                                                      25








                                                      25







                                                      Set is the good approach here, because it orders the variables, what seems to be your goal here. z,y,x is 0,1,3 whatever the order of the parameters.



                                                      >>> ["cdef"[i] for i in z,x,y]
                                                      ['c', 'd', 'f']


                                                      This way, the whole solution is O(n).






                                                      share|improve this answer















                                                      Set is the good approach here, because it orders the variables, what seems to be your goal here. z,y,x is 0,1,3 whatever the order of the parameters.



                                                      >>> ["cdef"[i] for i in z,x,y]
                                                      ['c', 'd', 'f']


                                                      This way, the whole solution is O(n).







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Apr 1 '18 at 13:10

























                                                      answered Jun 9 '15 at 20:46









                                                      B. M.B. M.

                                                      14.1k2 gold badges22 silver badges37 bronze badges




                                                      14.1k2 gold badges22 silver badges37 bronze badges







                                                      • 4





                                                        You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

                                                        – Raniz
                                                        Jun 10 '15 at 4:19












                                                      • 4





                                                        You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

                                                        – Raniz
                                                        Jun 10 '15 at 4:19







                                                      4




                                                      4





                                                      You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

                                                      – Raniz
                                                      Jun 10 '15 at 4:19





                                                      You should add a description of what your code accomplishes and how it does it. Short answers using only code is discouraged

                                                      – Raniz
                                                      Jun 10 '15 at 4:19











                                                      25














                                                      If you want to use if, else statements following is another solution:



                                                      myList = []
                                                      aList = [0, 1, 3]

                                                      for l in aList:
                                                      if l==0: myList.append('c')
                                                      elif l==1: myList.append('d')
                                                      elif l==2: myList.append('e')
                                                      elif l==3: myList.append('f')

                                                      print(myList)





                                                      share|improve this answer





























                                                        25














                                                        If you want to use if, else statements following is another solution:



                                                        myList = []
                                                        aList = [0, 1, 3]

                                                        for l in aList:
                                                        if l==0: myList.append('c')
                                                        elif l==1: myList.append('d')
                                                        elif l==2: myList.append('e')
                                                        elif l==3: myList.append('f')

                                                        print(myList)





                                                        share|improve this answer



























                                                          25












                                                          25








                                                          25







                                                          If you want to use if, else statements following is another solution:



                                                          myList = []
                                                          aList = [0, 1, 3]

                                                          for l in aList:
                                                          if l==0: myList.append('c')
                                                          elif l==1: myList.append('d')
                                                          elif l==2: myList.append('e')
                                                          elif l==3: myList.append('f')

                                                          print(myList)





                                                          share|improve this answer















                                                          If you want to use if, else statements following is another solution:



                                                          myList = []
                                                          aList = [0, 1, 3]

                                                          for l in aList:
                                                          if l==0: myList.append('c')
                                                          elif l==1: myList.append('d')
                                                          elif l==2: myList.append('e')
                                                          elif l==3: myList.append('f')

                                                          print(myList)






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Sep 4 '18 at 3:53









                                                          Vishvajit Pathak

                                                          1,27014 silver badges13 bronze badges




                                                          1,27014 silver badges13 bronze badges










                                                          answered Apr 10 '15 at 3:29









                                                          hamidhamid

                                                          3843 silver badges6 bronze badges




                                                          3843 silver badges6 bronze badges





















                                                              25














                                                              All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in x,y,z solution put forward by Martijn Pieters.

                                                              What they ignore is the broader implication of the question:
                                                              How do I test one variable against multiple values?

                                                              The solution provided will not work for partial hits if using strings for example:

                                                              Test if the string "Wild" is in multiple values



                                                              >>> x = "Wild things"
                                                              >>> y = "throttle it back"
                                                              >>> z = "in the beginning"
                                                              >>> if "Wild" in x, y, z: print (True)
                                                              ...


                                                              or



                                                              >>> x = "Wild things"
                                                              >>> y = "throttle it back"
                                                              >>> z = "in the beginning"
                                                              >>> if "Wild" in [x, y, z]: print (True)
                                                              ...


                                                              for this scenario it's easiest to convert to a string



                                                              >>> [x, y, z]
                                                              ['Wild things', 'throttle it back', 'in the beginning']
                                                              >>> x, y, z
                                                              'in the beginning', 'throttle it back', 'Wild things'
                                                              >>>

                                                              >>> if "Wild" in str([x, y, z]): print (True)
                                                              ...
                                                              True
                                                              >>> if "Wild" in str(x, y, z): print (True)
                                                              ...
                                                              True


                                                              It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:



                                                              >>> x=['Wild things', 'throttle it back', 'in the beginning']
                                                              >>> if "rot" in str(x): print(True)
                                                              ...
                                                              True


                                                              the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.

                                                              The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.






                                                              share|improve this answer





























                                                                25














                                                                All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in x,y,z solution put forward by Martijn Pieters.

                                                                What they ignore is the broader implication of the question:
                                                                How do I test one variable against multiple values?

                                                                The solution provided will not work for partial hits if using strings for example:

                                                                Test if the string "Wild" is in multiple values



                                                                >>> x = "Wild things"
                                                                >>> y = "throttle it back"
                                                                >>> z = "in the beginning"
                                                                >>> if "Wild" in x, y, z: print (True)
                                                                ...


                                                                or



                                                                >>> x = "Wild things"
                                                                >>> y = "throttle it back"
                                                                >>> z = "in the beginning"
                                                                >>> if "Wild" in [x, y, z]: print (True)
                                                                ...


                                                                for this scenario it's easiest to convert to a string



                                                                >>> [x, y, z]
                                                                ['Wild things', 'throttle it back', 'in the beginning']
                                                                >>> x, y, z
                                                                'in the beginning', 'throttle it back', 'Wild things'
                                                                >>>

                                                                >>> if "Wild" in str([x, y, z]): print (True)
                                                                ...
                                                                True
                                                                >>> if "Wild" in str(x, y, z): print (True)
                                                                ...
                                                                True


                                                                It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:



                                                                >>> x=['Wild things', 'throttle it back', 'in the beginning']
                                                                >>> if "rot" in str(x): print(True)
                                                                ...
                                                                True


                                                                the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.

                                                                The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.






                                                                share|improve this answer



























                                                                  25












                                                                  25








                                                                  25







                                                                  All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in x,y,z solution put forward by Martijn Pieters.

                                                                  What they ignore is the broader implication of the question:
                                                                  How do I test one variable against multiple values?

                                                                  The solution provided will not work for partial hits if using strings for example:

                                                                  Test if the string "Wild" is in multiple values



                                                                  >>> x = "Wild things"
                                                                  >>> y = "throttle it back"
                                                                  >>> z = "in the beginning"
                                                                  >>> if "Wild" in x, y, z: print (True)
                                                                  ...


                                                                  or



                                                                  >>> x = "Wild things"
                                                                  >>> y = "throttle it back"
                                                                  >>> z = "in the beginning"
                                                                  >>> if "Wild" in [x, y, z]: print (True)
                                                                  ...


                                                                  for this scenario it's easiest to convert to a string



                                                                  >>> [x, y, z]
                                                                  ['Wild things', 'throttle it back', 'in the beginning']
                                                                  >>> x, y, z
                                                                  'in the beginning', 'throttle it back', 'Wild things'
                                                                  >>>

                                                                  >>> if "Wild" in str([x, y, z]): print (True)
                                                                  ...
                                                                  True
                                                                  >>> if "Wild" in str(x, y, z): print (True)
                                                                  ...
                                                                  True


                                                                  It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:



                                                                  >>> x=['Wild things', 'throttle it back', 'in the beginning']
                                                                  >>> if "rot" in str(x): print(True)
                                                                  ...
                                                                  True


                                                                  the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.

                                                                  The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.






                                                                  share|improve this answer















                                                                  All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in x,y,z solution put forward by Martijn Pieters.

                                                                  What they ignore is the broader implication of the question:
                                                                  How do I test one variable against multiple values?

                                                                  The solution provided will not work for partial hits if using strings for example:

                                                                  Test if the string "Wild" is in multiple values



                                                                  >>> x = "Wild things"
                                                                  >>> y = "throttle it back"
                                                                  >>> z = "in the beginning"
                                                                  >>> if "Wild" in x, y, z: print (True)
                                                                  ...


                                                                  or



                                                                  >>> x = "Wild things"
                                                                  >>> y = "throttle it back"
                                                                  >>> z = "in the beginning"
                                                                  >>> if "Wild" in [x, y, z]: print (True)
                                                                  ...


                                                                  for this scenario it's easiest to convert to a string



                                                                  >>> [x, y, z]
                                                                  ['Wild things', 'throttle it back', 'in the beginning']
                                                                  >>> x, y, z
                                                                  'in the beginning', 'throttle it back', 'Wild things'
                                                                  >>>

                                                                  >>> if "Wild" in str([x, y, z]): print (True)
                                                                  ...
                                                                  True
                                                                  >>> if "Wild" in str(x, y, z): print (True)
                                                                  ...
                                                                  True


                                                                  It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:



                                                                  >>> x=['Wild things', 'throttle it back', 'in the beginning']
                                                                  >>> if "rot" in str(x): print(True)
                                                                  ...
                                                                  True


                                                                  the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.

                                                                  The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.







                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Sep 4 '18 at 11:59









                                                                  Vishvajit Pathak

                                                                  1,27014 silver badges13 bronze badges




                                                                  1,27014 silver badges13 bronze badges










                                                                  answered Sep 10 '16 at 15:44









                                                                  Rolf of SaxonyRolf of Saxony

                                                                  11k2 gold badges22 silver badges40 bronze badges




                                                                  11k2 gold badges22 silver badges40 bronze badges





















                                                                      22














                                                                      d = 0:'c', 1:'d', 2:'e', 3: 'f'
                                                                      x, y, z = (0, 1, 3)
                                                                      print [v for (k,v) in d.items() if x==k or y==k or z==k]





                                                                      share|improve this answer





























                                                                        22














                                                                        d = 0:'c', 1:'d', 2:'e', 3: 'f'
                                                                        x, y, z = (0, 1, 3)
                                                                        print [v for (k,v) in d.items() if x==k or y==k or z==k]





                                                                        share|improve this answer



























                                                                          22












                                                                          22








                                                                          22







                                                                          d = 0:'c', 1:'d', 2:'e', 3: 'f'
                                                                          x, y, z = (0, 1, 3)
                                                                          print [v for (k,v) in d.items() if x==k or y==k or z==k]





                                                                          share|improve this answer















                                                                          d = 0:'c', 1:'d', 2:'e', 3: 'f'
                                                                          x, y, z = (0, 1, 3)
                                                                          print [v for (k,v) in d.items() if x==k or y==k or z==k]






                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Feb 27 '15 at 1:48

























                                                                          answered Feb 27 '15 at 1:31









                                                                          Saksham VarmaSaksham Varma

                                                                          1,8247 silver badges14 bronze badges




                                                                          1,8247 silver badges14 bronze badges





















                                                                              22














                                                                              This code may be helpful



                                                                              L =x, y, z
                                                                              T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
                                                                              List2=[]
                                                                              for t in T :
                                                                              if t[0] in L :
                                                                              List2.append(t[1])
                                                                              break;





                                                                              share|improve this answer



























                                                                                22














                                                                                This code may be helpful



                                                                                L =x, y, z
                                                                                T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
                                                                                List2=[]
                                                                                for t in T :
                                                                                if t[0] in L :
                                                                                List2.append(t[1])
                                                                                break;





                                                                                share|improve this answer

























                                                                                  22












                                                                                  22








                                                                                  22







                                                                                  This code may be helpful



                                                                                  L =x, y, z
                                                                                  T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
                                                                                  List2=[]
                                                                                  for t in T :
                                                                                  if t[0] in L :
                                                                                  List2.append(t[1])
                                                                                  break;





                                                                                  share|improve this answer













                                                                                  This code may be helpful



                                                                                  L =x, y, z
                                                                                  T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
                                                                                  List2=[]
                                                                                  for t in T :
                                                                                  if t[0] in L :
                                                                                  List2.append(t[1])
                                                                                  break;






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Jun 29 '15 at 7:03









                                                                                  michael zxc858michael zxc858

                                                                                  2353 silver badges7 bronze badges




                                                                                  2353 silver badges7 bronze badges





















                                                                                      7














                                                                                      One line solution:



                                                                                      mylist = [0: 'c', 1: 'd', 2: 'e', 3: 'f'[i] for i in [0, 1, 2, 3] if i in (x, y, z)]


                                                                                      Or:



                                                                                      mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]





                                                                                      share|improve this answer



























                                                                                        7














                                                                                        One line solution:



                                                                                        mylist = [0: 'c', 1: 'd', 2: 'e', 3: 'f'[i] for i in [0, 1, 2, 3] if i in (x, y, z)]


                                                                                        Or:



                                                                                        mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]





                                                                                        share|improve this answer

























                                                                                          7












                                                                                          7








                                                                                          7







                                                                                          One line solution:



                                                                                          mylist = [0: 'c', 1: 'd', 2: 'e', 3: 'f'[i] for i in [0, 1, 2, 3] if i in (x, y, z)]


                                                                                          Or:



                                                                                          mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]





                                                                                          share|improve this answer













                                                                                          One line solution:



                                                                                          mylist = [0: 'c', 1: 'd', 2: 'e', 3: 'f'[i] for i in [0, 1, 2, 3] if i in (x, y, z)]


                                                                                          Or:



                                                                                          mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]






                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Jun 5 '17 at 6:50









                                                                                          Vinayak KaniyarakkalVinayak Kaniyarakkal

                                                                                          78012 silver badges20 bronze badges




                                                                                          78012 silver badges20 bronze badges





















                                                                                              6














                                                                                              You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.



                                                                                              mydict = 0:"c", 1:"d", 2:"e", 3:"f"
                                                                                              mylist= []

                                                                                              num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

                                                                                              for i in range(num_var):
                                                                                              ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
                                                                                              globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
                                                                                              mylist += mydict[globals()['var'+str('i').zfill(3)]]

                                                                                              print mylist
                                                                                              >>> ['c', 'd', 'f']





                                                                                              share|improve this answer



























                                                                                                6














                                                                                                You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.



                                                                                                mydict = 0:"c", 1:"d", 2:"e", 3:"f"
                                                                                                mylist= []

                                                                                                num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

                                                                                                for i in range(num_var):
                                                                                                ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
                                                                                                globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
                                                                                                mylist += mydict[globals()['var'+str('i').zfill(3)]]

                                                                                                print mylist
                                                                                                >>> ['c', 'd', 'f']





                                                                                                share|improve this answer

























                                                                                                  6












                                                                                                  6








                                                                                                  6







                                                                                                  You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.



                                                                                                  mydict = 0:"c", 1:"d", 2:"e", 3:"f"
                                                                                                  mylist= []

                                                                                                  num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

                                                                                                  for i in range(num_var):
                                                                                                  ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
                                                                                                  globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
                                                                                                  mylist += mydict[globals()['var'+str('i').zfill(3)]]

                                                                                                  print mylist
                                                                                                  >>> ['c', 'd', 'f']





                                                                                                  share|improve this answer













                                                                                                  You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.



                                                                                                  mydict = 0:"c", 1:"d", 2:"e", 3:"f"
                                                                                                  mylist= []

                                                                                                  num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

                                                                                                  for i in range(num_var):
                                                                                                  ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
                                                                                                  globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
                                                                                                  mylist += mydict[globals()['var'+str('i').zfill(3)]]

                                                                                                  print mylist
                                                                                                  >>> ['c', 'd', 'f']






                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Dec 3 '18 at 5:13









                                                                                                  Siddharth SatpathySiddharth Satpathy

                                                                                                  7852 gold badges9 silver badges18 bronze badges




                                                                                                  7852 gold badges9 silver badges18 bronze badges





















                                                                                                      5














                                                                                                      Maybe you need direct formula for output bits set.



                                                                                                      x=0 or y=0 or z=0 is equivalent to x*y*z = 0

                                                                                                      x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0

                                                                                                      x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0


                                                                                                      Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000



                                                                                                      Relation of isc (is 'c'):



                                                                                                      if xyz=0 then isc=1 else isc=0


                                                                                                      Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315



                                                                                                      [c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))



                                                                                                      [d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))



                                                                                                      ...



                                                                                                      Connect these formulas by following logic:



                                                                                                      • logic and is the sum of squares of equations

                                                                                                      • logic or is the product of equations

                                                                                                      and you'll have a total equation
                                                                                                      express sum and you have total formula of sum



                                                                                                      then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f



                                                                                                      After this you may form predefined array where index of string elements would correspond to ready string.



                                                                                                      array[sum] gives you the string.






                                                                                                      share|improve this answer





























                                                                                                        5














                                                                                                        Maybe you need direct formula for output bits set.



                                                                                                        x=0 or y=0 or z=0 is equivalent to x*y*z = 0

                                                                                                        x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0

                                                                                                        x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0


                                                                                                        Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000



                                                                                                        Relation of isc (is 'c'):



                                                                                                        if xyz=0 then isc=1 else isc=0


                                                                                                        Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315



                                                                                                        [c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))



                                                                                                        [d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))



                                                                                                        ...



                                                                                                        Connect these formulas by following logic:



                                                                                                        • logic and is the sum of squares of equations

                                                                                                        • logic or is the product of equations

                                                                                                        and you'll have a total equation
                                                                                                        express sum and you have total formula of sum



                                                                                                        then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f



                                                                                                        After this you may form predefined array where index of string elements would correspond to ready string.



                                                                                                        array[sum] gives you the string.






                                                                                                        share|improve this answer



























                                                                                                          5












                                                                                                          5








                                                                                                          5







                                                                                                          Maybe you need direct formula for output bits set.



                                                                                                          x=0 or y=0 or z=0 is equivalent to x*y*z = 0

                                                                                                          x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0

                                                                                                          x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0


                                                                                                          Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000



                                                                                                          Relation of isc (is 'c'):



                                                                                                          if xyz=0 then isc=1 else isc=0


                                                                                                          Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315



                                                                                                          [c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))



                                                                                                          [d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))



                                                                                                          ...



                                                                                                          Connect these formulas by following logic:



                                                                                                          • logic and is the sum of squares of equations

                                                                                                          • logic or is the product of equations

                                                                                                          and you'll have a total equation
                                                                                                          express sum and you have total formula of sum



                                                                                                          then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f



                                                                                                          After this you may form predefined array where index of string elements would correspond to ready string.



                                                                                                          array[sum] gives you the string.






                                                                                                          share|improve this answer















                                                                                                          Maybe you need direct formula for output bits set.



                                                                                                          x=0 or y=0 or z=0 is equivalent to x*y*z = 0

                                                                                                          x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0

                                                                                                          x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0


                                                                                                          Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000



                                                                                                          Relation of isc (is 'c'):



                                                                                                          if xyz=0 then isc=1 else isc=0


                                                                                                          Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315



                                                                                                          [c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))



                                                                                                          [d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))



                                                                                                          ...



                                                                                                          Connect these formulas by following logic:



                                                                                                          • logic and is the sum of squares of equations

                                                                                                          • logic or is the product of equations

                                                                                                          and you'll have a total equation
                                                                                                          express sum and you have total formula of sum



                                                                                                          then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f



                                                                                                          After this you may form predefined array where index of string elements would correspond to ready string.



                                                                                                          array[sum] gives you the string.







                                                                                                          share|improve this answer














                                                                                                          share|improve this answer



                                                                                                          share|improve this answer








                                                                                                          edited Apr 10 at 17:49









                                                                                                          tripleee

                                                                                                          100k15 gold badges146 silver badges197 bronze badges




                                                                                                          100k15 gold badges146 silver badges197 bronze badges










                                                                                                          answered Feb 17 at 17:55









                                                                                                          SergeiSergei

                                                                                                          1,9351 gold badge21 silver badges36 bronze badges




                                                                                                          1,9351 gold badge21 silver badges36 bronze badges





















                                                                                                              4














                                                                                                              It can be done easily as



                                                                                                              for value in [var1,var2,var3]:
                                                                                                              li.append("targetValue")





                                                                                                              share|improve this answer



























                                                                                                                4














                                                                                                                It can be done easily as



                                                                                                                for value in [var1,var2,var3]:
                                                                                                                li.append("targetValue")





                                                                                                                share|improve this answer

























                                                                                                                  4












                                                                                                                  4








                                                                                                                  4







                                                                                                                  It can be done easily as



                                                                                                                  for value in [var1,var2,var3]:
                                                                                                                  li.append("targetValue")





                                                                                                                  share|improve this answer













                                                                                                                  It can be done easily as



                                                                                                                  for value in [var1,var2,var3]:
                                                                                                                  li.append("targetValue")






                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Nov 6 '18 at 14:26









                                                                                                                  SeenivasanSeenivasan

                                                                                                                  7821 gold badge8 silver badges18 bronze badges




                                                                                                                  7821 gold badge8 silver badges18 bronze badges





















                                                                                                                      3














                                                                                                                      The most mnemonic way of representing your pseudo-code in Python would be:



                                                                                                                      x = 0
                                                                                                                      y = 1
                                                                                                                      z = 3
                                                                                                                      mylist = []

                                                                                                                      if any(v == 0 for v in (x, y, z)):
                                                                                                                      mylist.append("c")
                                                                                                                      if any(v == 1 for v in (x, y, z)):
                                                                                                                      mylist.append("d")
                                                                                                                      if any(v == 2 for v in (x, y, z)):
                                                                                                                      mylist.append("e")
                                                                                                                      if any(v == 3 for v in (x, y, z)):
                                                                                                                      mylist.append("f")





                                                                                                                      share|improve this answer























                                                                                                                      • This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                                                                                                                        – imposeren
                                                                                                                        May 4 at 4:47















                                                                                                                      3














                                                                                                                      The most mnemonic way of representing your pseudo-code in Python would be:



                                                                                                                      x = 0
                                                                                                                      y = 1
                                                                                                                      z = 3
                                                                                                                      mylist = []

                                                                                                                      if any(v == 0 for v in (x, y, z)):
                                                                                                                      mylist.append("c")
                                                                                                                      if any(v == 1 for v in (x, y, z)):
                                                                                                                      mylist.append("d")
                                                                                                                      if any(v == 2 for v in (x, y, z)):
                                                                                                                      mylist.append("e")
                                                                                                                      if any(v == 3 for v in (x, y, z)):
                                                                                                                      mylist.append("f")





                                                                                                                      share|improve this answer























                                                                                                                      • This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                                                                                                                        – imposeren
                                                                                                                        May 4 at 4:47













                                                                                                                      3












                                                                                                                      3








                                                                                                                      3







                                                                                                                      The most mnemonic way of representing your pseudo-code in Python would be:



                                                                                                                      x = 0
                                                                                                                      y = 1
                                                                                                                      z = 3
                                                                                                                      mylist = []

                                                                                                                      if any(v == 0 for v in (x, y, z)):
                                                                                                                      mylist.append("c")
                                                                                                                      if any(v == 1 for v in (x, y, z)):
                                                                                                                      mylist.append("d")
                                                                                                                      if any(v == 2 for v in (x, y, z)):
                                                                                                                      mylist.append("e")
                                                                                                                      if any(v == 3 for v in (x, y, z)):
                                                                                                                      mylist.append("f")





                                                                                                                      share|improve this answer













                                                                                                                      The most mnemonic way of representing your pseudo-code in Python would be:



                                                                                                                      x = 0
                                                                                                                      y = 1
                                                                                                                      z = 3
                                                                                                                      mylist = []

                                                                                                                      if any(v == 0 for v in (x, y, z)):
                                                                                                                      mylist.append("c")
                                                                                                                      if any(v == 1 for v in (x, y, z)):
                                                                                                                      mylist.append("d")
                                                                                                                      if any(v == 2 for v in (x, y, z)):
                                                                                                                      mylist.append("e")
                                                                                                                      if any(v == 3 for v in (x, y, z)):
                                                                                                                      mylist.append("f")






                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered Aug 6 '18 at 6:26









                                                                                                                      rsalmeirsalmei

                                                                                                                      1998 bronze badges




                                                                                                                      1998 bronze badges












                                                                                                                      • This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                                                                                                                        – imposeren
                                                                                                                        May 4 at 4:47

















                                                                                                                      • This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                                                                                                                        – imposeren
                                                                                                                        May 4 at 4:47
















                                                                                                                      This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                                                                                                                      – imposeren
                                                                                                                      May 4 at 4:47





                                                                                                                      This approach is more universal than ` if 2 in (x, y, z): mylist.append('e')` because allows arbitrary comparisons (e.g. if any(v >= 42 for v in (x, y, z)): ). And performance of all 3 methods (2 in x,y,z, 2 in (x,y,z), any(_v == 2 for _v in (x,y,z))) seems to be almost the same in CPython3.6 (see Gist)

                                                                                                                      – imposeren
                                                                                                                      May 4 at 4:47











                                                                                                                      3














                                                                                                                      Looks like you're building some kind of Caesar cipher.



                                                                                                                      A much more generalized approach is this:



                                                                                                                      input_values = (0, 1, 3)
                                                                                                                      origo = ord('c')
                                                                                                                      [chr(val + origo) for val in inputs]


                                                                                                                      outputs



                                                                                                                      ['c', 'd', 'f']


                                                                                                                      Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.



                                                                                                                      If this is what you want, the final line can be changed to:



                                                                                                                      sorted([chr(val + origo) for val in inputs])





                                                                                                                      share|improve this answer



























                                                                                                                        3














                                                                                                                        Looks like you're building some kind of Caesar cipher.



                                                                                                                        A much more generalized approach is this:



                                                                                                                        input_values = (0, 1, 3)
                                                                                                                        origo = ord('c')
                                                                                                                        [chr(val + origo) for val in inputs]


                                                                                                                        outputs



                                                                                                                        ['c', 'd', 'f']


                                                                                                                        Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.



                                                                                                                        If this is what you want, the final line can be changed to:



                                                                                                                        sorted([chr(val + origo) for val in inputs])





                                                                                                                        share|improve this answer

























                                                                                                                          3












                                                                                                                          3








                                                                                                                          3







                                                                                                                          Looks like you're building some kind of Caesar cipher.



                                                                                                                          A much more generalized approach is this:



                                                                                                                          input_values = (0, 1, 3)
                                                                                                                          origo = ord('c')
                                                                                                                          [chr(val + origo) for val in inputs]


                                                                                                                          outputs



                                                                                                                          ['c', 'd', 'f']


                                                                                                                          Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.



                                                                                                                          If this is what you want, the final line can be changed to:



                                                                                                                          sorted([chr(val + origo) for val in inputs])





                                                                                                                          share|improve this answer













                                                                                                                          Looks like you're building some kind of Caesar cipher.



                                                                                                                          A much more generalized approach is this:



                                                                                                                          input_values = (0, 1, 3)
                                                                                                                          origo = ord('c')
                                                                                                                          [chr(val + origo) for val in inputs]


                                                                                                                          outputs



                                                                                                                          ['c', 'd', 'f']


                                                                                                                          Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.



                                                                                                                          If this is what you want, the final line can be changed to:



                                                                                                                          sorted([chr(val + origo) for val in inputs])






                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Aug 27 '18 at 9:45









                                                                                                                          firelynxfirelynx

                                                                                                                          16.4k3 gold badges68 silver badges81 bronze badges




                                                                                                                          16.4k3 gold badges68 silver badges81 bronze badges





















                                                                                                                              3














                                                                                                                              To test multiple variables with one single value: if 1 in a,b,c:



                                                                                                                              To test multiple values with one variable: if a in 1, 2, 3:






                                                                                                                              share|improve this answer



























                                                                                                                                3














                                                                                                                                To test multiple variables with one single value: if 1 in a,b,c:



                                                                                                                                To test multiple values with one variable: if a in 1, 2, 3:






                                                                                                                                share|improve this answer

























                                                                                                                                  3












                                                                                                                                  3








                                                                                                                                  3







                                                                                                                                  To test multiple variables with one single value: if 1 in a,b,c:



                                                                                                                                  To test multiple values with one variable: if a in 1, 2, 3:






                                                                                                                                  share|improve this answer













                                                                                                                                  To test multiple variables with one single value: if 1 in a,b,c:



                                                                                                                                  To test multiple values with one variable: if a in 1, 2, 3:







                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Sep 20 '18 at 2:18









                                                                                                                                  alaminalamin

                                                                                                                                  1,1021 gold badge15 silver badges24 bronze badges




                                                                                                                                  1,1021 gold badge15 silver badges24 bronze badges





















                                                                                                                                      1














                                                                                                                                      You can use dictionary :



                                                                                                                                      x = 0
                                                                                                                                      y = 1
                                                                                                                                      z = 3
                                                                                                                                      list=[]
                                                                                                                                      dict = 0: 'c', 1: 'd', 2: 'e', 3: 'f'
                                                                                                                                      if x in dict:
                                                                                                                                      list.append(dict[x])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      if y in dict:
                                                                                                                                      list.append(dict[y])
                                                                                                                                      else:
                                                                                                                                      pass
                                                                                                                                      if z in dict:
                                                                                                                                      list.append(dict[z])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      print list





                                                                                                                                      share|improve this answer























                                                                                                                                      • This may append same more then once this. Set?

                                                                                                                                        – Sergei
                                                                                                                                        Feb 19 at 4:49















                                                                                                                                      1














                                                                                                                                      You can use dictionary :



                                                                                                                                      x = 0
                                                                                                                                      y = 1
                                                                                                                                      z = 3
                                                                                                                                      list=[]
                                                                                                                                      dict = 0: 'c', 1: 'd', 2: 'e', 3: 'f'
                                                                                                                                      if x in dict:
                                                                                                                                      list.append(dict[x])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      if y in dict:
                                                                                                                                      list.append(dict[y])
                                                                                                                                      else:
                                                                                                                                      pass
                                                                                                                                      if z in dict:
                                                                                                                                      list.append(dict[z])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      print list





                                                                                                                                      share|improve this answer























                                                                                                                                      • This may append same more then once this. Set?

                                                                                                                                        – Sergei
                                                                                                                                        Feb 19 at 4:49













                                                                                                                                      1












                                                                                                                                      1








                                                                                                                                      1







                                                                                                                                      You can use dictionary :



                                                                                                                                      x = 0
                                                                                                                                      y = 1
                                                                                                                                      z = 3
                                                                                                                                      list=[]
                                                                                                                                      dict = 0: 'c', 1: 'd', 2: 'e', 3: 'f'
                                                                                                                                      if x in dict:
                                                                                                                                      list.append(dict[x])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      if y in dict:
                                                                                                                                      list.append(dict[y])
                                                                                                                                      else:
                                                                                                                                      pass
                                                                                                                                      if z in dict:
                                                                                                                                      list.append(dict[z])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      print list





                                                                                                                                      share|improve this answer













                                                                                                                                      You can use dictionary :



                                                                                                                                      x = 0
                                                                                                                                      y = 1
                                                                                                                                      z = 3
                                                                                                                                      list=[]
                                                                                                                                      dict = 0: 'c', 1: 'd', 2: 'e', 3: 'f'
                                                                                                                                      if x in dict:
                                                                                                                                      list.append(dict[x])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      if y in dict:
                                                                                                                                      list.append(dict[y])
                                                                                                                                      else:
                                                                                                                                      pass
                                                                                                                                      if z in dict:
                                                                                                                                      list.append(dict[z])
                                                                                                                                      else:
                                                                                                                                      pass

                                                                                                                                      print list






                                                                                                                                      share|improve this answer












                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer










                                                                                                                                      answered Jul 31 '18 at 16:54









                                                                                                                                      Rohit GawasRohit Gawas

                                                                                                                                      593 bronze badges




                                                                                                                                      593 bronze badges












                                                                                                                                      • This may append same more then once this. Set?

                                                                                                                                        – Sergei
                                                                                                                                        Feb 19 at 4:49

















                                                                                                                                      • This may append same more then once this. Set?

                                                                                                                                        – Sergei
                                                                                                                                        Feb 19 at 4:49
















                                                                                                                                      This may append same more then once this. Set?

                                                                                                                                      – Sergei
                                                                                                                                      Feb 19 at 4:49





                                                                                                                                      This may append same more then once this. Set?

                                                                                                                                      – Sergei
                                                                                                                                      Feb 19 at 4:49











                                                                                                                                      0














                                                                                                                                      This will help you.



                                                                                                                                      def test_fun(val):
                                                                                                                                      x = 0
                                                                                                                                      y = 1
                                                                                                                                      z = 2
                                                                                                                                      myList = []
                                                                                                                                      if val in (x, y, z) and val == 0:
                                                                                                                                      myList.append("C")
                                                                                                                                      if val in (x, y, z) and val == 1:
                                                                                                                                      myList.append("D")
                                                                                                                                      if val in (x, y, z) and val == 2:
                                                                                                                                      myList.append("E")

                                                                                                                                      test_fun(2);





                                                                                                                                      share|improve this answer





























                                                                                                                                        0














                                                                                                                                        This will help you.



                                                                                                                                        def test_fun(val):
                                                                                                                                        x = 0
                                                                                                                                        y = 1
                                                                                                                                        z = 2
                                                                                                                                        myList = []
                                                                                                                                        if val in (x, y, z) and val == 0:
                                                                                                                                        myList.append("C")
                                                                                                                                        if val in (x, y, z) and val == 1:
                                                                                                                                        myList.append("D")
                                                                                                                                        if val in (x, y, z) and val == 2:
                                                                                                                                        myList.append("E")

                                                                                                                                        test_fun(2);





                                                                                                                                        share|improve this answer



























                                                                                                                                          0












                                                                                                                                          0








                                                                                                                                          0







                                                                                                                                          This will help you.



                                                                                                                                          def test_fun(val):
                                                                                                                                          x = 0
                                                                                                                                          y = 1
                                                                                                                                          z = 2
                                                                                                                                          myList = []
                                                                                                                                          if val in (x, y, z) and val == 0:
                                                                                                                                          myList.append("C")
                                                                                                                                          if val in (x, y, z) and val == 1:
                                                                                                                                          myList.append("D")
                                                                                                                                          if val in (x, y, z) and val == 2:
                                                                                                                                          myList.append("E")

                                                                                                                                          test_fun(2);





                                                                                                                                          share|improve this answer















                                                                                                                                          This will help you.



                                                                                                                                          def test_fun(val):
                                                                                                                                          x = 0
                                                                                                                                          y = 1
                                                                                                                                          z = 2
                                                                                                                                          myList = []
                                                                                                                                          if val in (x, y, z) and val == 0:
                                                                                                                                          myList.append("C")
                                                                                                                                          if val in (x, y, z) and val == 1:
                                                                                                                                          myList.append("D")
                                                                                                                                          if val in (x, y, z) and val == 2:
                                                                                                                                          myList.append("E")

                                                                                                                                          test_fun(2);






                                                                                                                                          share|improve this answer














                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer








                                                                                                                                          edited Apr 8 at 5:18









                                                                                                                                          Karan Shah

                                                                                                                                          4111 bronze badges




                                                                                                                                          4111 bronze badges










                                                                                                                                          answered Apr 5 at 22:03









                                                                                                                                          MayurMayur

                                                                                                                                          3595 silver badges25 bronze badges




                                                                                                                                          3595 silver badges25 bronze badges















                                                                                                                                              protected by Martijn Pieters Mar 8 '15 at 1:18



                                                                                                                                              Thank you for your interest in this question.
                                                                                                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                              Would you like to answer one of these unanswered questions instead?



                                                                                                                                              Popular posts from this blog

                                                                                                                                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                                                                                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                                                                                                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript