varad
varad

Reputation: 8029

python for loop except

I have a list

my_list = ['a', 'b', 'c']
for my_value is my_list except'a':
    print(my_value)

Here I want to iterate over all values and print them excpet 'a'

How can I do this ? I know it can be done using if condition but I want to know if I can do it in one line if for my_value in my_list except 'a'

Upvotes: 3

Views: 14749

Answers (1)

nigel222
nigel222

Reputation: 8202

It can be done in one line, although it's horrible programming style to do so.

for value in [ v for v in my_list if v != 'a' ]

What I'd recommend is two lines. if ... : continue immediately starts the next iteration of the loop, so the rest of the loop body is skipped.

for value in my_list:
   if value == 'a': continue 
   # rest of loop code

There's also an elegant one-liner that is not quite an answer to the problem posed. This is

for value in set(my_list) - {'a'}

The reasons it is not an answer are (a) that sets are un-ordered, so the for-loop doesn't necessarily process elements of my_list in the order that they are stored in my_list. And crucially (b), that a set cannot contain duplicates, so set(['c','d','c']) == {'c','d'} and the loop will process duplicates only once, not multiple times. Sometimes, that's a rather desirable consequence.

Upvotes: 9

Related Questions