Search code examples
pythoncontrol-flow

Python for item in listA AND listB


This question may be very straightforward and obvious to some people, but for whatever reason I have been unable to find the answer online. I did not find my answer by tinkering with IDLE and trying to understand how it worked. How does a for loop work when multiple items are specified?

a = [1,2,3,4,5]
b = [6,7,8,9,0]
    for item in a and b:
        print 'why does this setup give the list b but nothing from a?'

Followup Questions:

1) What might happen with other operators, such as or and not?

2) Is this proper usage, even? If so, is it messy, unsafe, or frowned upon?


Solution

  • So, you have two lists:

    >>> a = [1,2,3,4,5]
    >>> b = [6,7,8,9,0]
    

    ... and you want to iterate over a and b. So what is a and b, exactly?

    >>> a and b
    [6, 7, 8, 9, 0]
    

    That might look odd, but it's the result of two facts about Python:

    1. Every object is either True-ish or False-ish. For example:

      >>> bool(a)
      True
      >>> bool(b)
      True
      

      In fact, all lists except the empty list [] are True-ish.

    2. Python uses short-circuit evaluation, which means that, for a and b, it:

      • Checks whether a is True-ish or False-ish

      • If a is False-ish, evaluates to a

      • If a is True-ish, evaluates to b

      Following those rules, you should be able to see why a and b evaluates to [6, 7, 8, 9, 0] in your case (and following the same rules for combinations of the actual values True and False will show you that short-circuit evaluation does make sense).

    If what you want to actually do is iterate trough the items in a and then those in b, you can just use the + operator to concatenate them:

    >>> for item in a + b:
    ...     print item,
    ... 
    1 2 3 4 5 6 7 8 9 0
    

    As for your followup questions:

    What might happen with other operators, such as or and not?

    or's rules for short-circuit evaluation are different (you can look them up for yourself or just follow the link above), and in your case a or b evaluates to [1, 2, 3, 4, 5] (in other words, a).

    not always returns True for a False-ish value and False for a True-ish value, and since you can't iterate over True or False, you'll get a TypeError.

    Is this proper usage, even? If so, is it messy, unsafe, or frowned upon?

    Well, there's nothing illegal about it, but as you can see, it doesn't do what you want. There are circumstances where (ab)using short-circuit evaluation to choose an iterable over which to iterate might be helpful, but this isn't one of them.