Pythonic way to combine FOR loop and IF statement Pythonic way to combine FOR loop and IF statement python python

Pythonic way to combine FOR loop and IF statement


You can use generator expressions like this:

gen = (x for x in xyz if x not in a)for x in gen:    print(x)


As per The Zen of Python (if you are wondering whether your code is "Pythonic", that's the place to go):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Flat is better than nested.
  • Readability counts.

The Pythonic way of getting the sorted intersection of two sets is:

>>> sorted(set(a).intersection(xyz))[0, 4, 6, 7, 9]

Or those elements that are xyz but not in a:

>>> sorted(set(xyz).difference(a))[12, 242]

But for a more complicated loop you may want to flatten it by iterating over a well-named generator expression and/or calling out to a well-named function. Trying to fit everything on one line is rarely "Pythonic".


Update following additional comments on your question and the accepted answer

I'm not sure what you are trying to do with enumerate, but if a is a dictionary, you probably want to use the keys, like this:

>>> a = {...     2: 'Turtle Doves',...     3: 'French Hens',...     4: 'Colly Birds',...     5: 'Gold Rings',...     6: 'Geese-a-Laying',...     7: 'Swans-a-Swimming',...     8: 'Maids-a-Milking',...     9: 'Ladies Dancing',...     0: 'Camel Books',... }>>>>>> xyz = [0, 12, 4, 6, 242, 7, 9]>>>>>> known_things = sorted(set(a.iterkeys()).intersection(xyz))>>> unknown_things = sorted(set(xyz).difference(a.iterkeys()))>>>>>> for thing in known_things:...     print 'I know about', a[thing]...I know about Camel BooksI know about Colly BirdsI know about Geese-a-LayingI know about Swans-a-SwimmingI know about Ladies Dancing>>> print '...but...'...but...>>>>>> for thing in unknown_things:...     print "I don't know what happened on the {0}th day of Christmas".format(thing)...I don't know what happened on the 12th day of ChristmasI don't know what happened on the 242th day of Christmas


The following is a simplification/one liner from the accepted answer:

a = [2,3,4,5,6,7,8,9,0]xyz = [0,12,4,6,242,7,9]for x in (x for x in xyz if x not in a):    print(x)12242

Notice that the generator was kept inline. This was tested on python2.7 and python3.6 (notice the parens in the print ;) )


matomo