-3

I have the following for and if condition,for loop followed by an if condition, any suggestions on how can i combine them in one line?

for x in ids:
   if x!=12345
carte blanche
  • 10,796
  • 14
  • 46
  • 65

1 Answers1

4
for x in (i for i in ids if i!=12345):
    # do stuff

In [37]: ids
Out[37]: [12343, 12344, 12345, 12346, 12347, 12348]

In [38]: for x in (i for i in ids if i!=12345):
   ....:     print x
   ....:     
12343
12344
12346
12347
12348
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • above is not working..i still see the for loop is being entered eventhough i = 12345 – carte blanche Jul 19 '13 at 02:53
  • I have a feeling that you're trying to do something a bit more complex than you initially let on. Why don't you edit an example into your post and I'll update my answer. – inspectorG4dget Jul 19 '13 at 02:55
  • no..nothing of that sort..i just dont want to enter the loop when i =12345 – carte blanche Jul 19 '13 at 02:56
  • 2
    One possibility is that the `id` is actually a string, and since `'12345' != 12345`, the test doesn't actually rule anything out. – DSM Jul 19 '13 at 03:03
  • I'm not sure this is a good idea. I like list comprehensions and generator comprehensions, but this is a lot like having two loops (one interleaved with the other) where you only need one. Maybe Python should allow an `if` clause in a `for` loop, for (probably minor) conciseness gains and for symmetry with comprehensions. Of course that's not an answer here. –  Jul 19 '13 at 03:13
  • 1
    @Steve314: the whole comprehension syntax was born out of the mathematical expression of sets, which effectively is a loop and bunch of filters (`if`s). Not sure how easy it would be to implement a full on set notation syntax, though – inspectorG4dget Jul 19 '13 at 03:16
  • 1
    @inspectorG4dget - I'm not suggesting full on set notation syntax or any change to list/generator comprehensions at all. I'm suggesting that the conventional `for` loop might be extended to support all or some of the flexibility of a list/generator comprehension, so you could e.g. write `for i in xs if pred(i) :` on a single line with one colon, rather than `for i in (j for j in xs if pred(j)) :` - eliminating the need for the comprehension. –  Jul 19 '13 at 16:20
  • @Steve314: that's interesting indeed. That idea hadn't occurred to me. I wonder if you could propose a PEP for that – inspectorG4dget Jul 19 '13 at 16:23
  • @inspectorG4dget - possibly - *after* I move home over the next couple of weeks, though. Also, I'm not sure that putting the `if` on the next line is a problem, and [the duplicate](http://stackoverflow.com/questions/6981717/pythonic-way-to-combine-for-loop-and-if-statement) suggests I'm not the first to think of it, so it has probably already have been considered and rejected. –  Jul 19 '13 at 16:35