20

I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:

for record in [x for x in records.split("\n") if x.strip() != '']:

I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:

for record in records.split("\n") if x.strip() != '']:

So what do the brackets do []? and why do we have x twice in x for x in records.split....

Thanks

Mo.
  • 40,243
  • 37
  • 86
  • 131
  • It's a list comprehension, see related: http://stackoverflow.com/questions/16341775/what-is-the-advantage-of-a-list-comprehension-vs-for-loop – EdChum Jun 05 '15 at 15:26
  • EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists. – Ami Tavory Jun 05 '15 at 15:28
  • 2
    Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for. – Mo. Jun 05 '15 at 15:38
  • @Mo. see: http://stackoverflow.com/questions/38229059/understanding-this-line-list-of-tuples-x-y-for-x-y-label-in-data-one – oba2311 Mar 08 '17 at 13:24

2 Answers2

42

The "brackets" in your example constructs a new list from an old one, this is called list comprehension.

The basic idea with [f(x) for x in xs if condition] is:

def list_comprehension(xs):
    result = []
    for x in xs:
        if condition:
            result.append(f(x))
    return result

The f(x) can be any expression, containing x or not.

ʇolɐǝz ǝɥʇ qoq
  • 717
  • 1
  • 15
  • 30
folkol
  • 4,752
  • 22
  • 25
2

That's a list comprehension, a neat way of creating lists with certain conditions on the fly.

You can make it a short form of this:

a = []
for record in records.split("\n"):
    if record.strip() != '':
        a.append(record)

for record in a:
    # do something
Zizouz212
  • 4,908
  • 5
  • 42
  • 66