Python triple iteration with list

Is triple iteration possible? The simplest version of what I mean, although this specific example could be made better:

c = 0 list1 = [4, 6, 7, 3, 4, 5, 3, 4] c += 1 if 4 == i for i in list1 else 0 

A more practical example:

 strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair'] counter = 0 counter += 1 if True == i.startswith('U') for i in strList else 0 return counter 
+3
python iteration ternary list-comprehension
source share
3 answers

Your "practical example" is written as:

 >>> strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair'] >>> sum(1 for el in strList if el.startswith('U')) 2 

Another example (if I understood correctly):

 >>> list1 = [4, 6, 7, 3, 4, 5, 3, 4] >>> list1.count(4) 3 

(or just strList example, but nothing wrong with using inline methods)

+5
source share

@Jon Clements gave you a great answer: how to solve a problem using the Python idiom. If other Python programmers look at its code, they will immediately understand it. This is just the right way to do this using Python.

To answer your real question: no, this does not work. The ternary operator has the following form:

 expr1 if condition else expr2 

condition should be something that evaluates to bool . The triple expression selects one of expr1 and expr2 and that is it.

When I tried an expression like c += 1 if condition else 0 , I was surprised that it worked, and noted that in the first version of this answer. @TokenMacGuy noted that the following is actually happening:

 c += (1 if condition else 0) 

That way, you can never do what you are trying to do, even if you put the right condition in place of some kind of loop. The above case will work, but something like this will fail:

 c += 1 if condition else x += 2 # syntax error on x += 2 

This is because Python does not consider the assignment operator to be an expression.

You cannot make this common mistake:

 if x = 3: # syntax error! Cannot put assignment statement here print("x: {}".format(x)) 

Here, the programmer most likely wanted x == 3 to check the value, but typed x = 3 . Python protects this error, not counting the assignment to an expression.

You cannot do this by mistake, and you cannot do this either.

+1
source share

You can also select your list items and accept the number of items in the list.

 strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair'] len([k for k in strList if k.startswith('U')]) 
0
source share

All Articles