What do [] brackets in a for loop in python mean?

Posted on

Question :

What do [] brackets in a for loop in python mean?

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

Asked By: Mo.

||

Answer #1:

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.

Answered By: folkol

Answer #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
Answered By: Zizouz212

Answer #3:

The square brackets ( [] ) usually signal a list in Python.

Answered By: uniqueusername

Leave a Reply

Your email address will not be published. Required fields are marked *