Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 887
Mo. Avatar asked Jun 05 '15 15:06

Mo.


People also ask

What do [] brackets mean in Python?

Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.

What is the difference between () and [] in Python?

() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.

What are {} brackets used for?

Brackets are used to insert explanations, corrections, clarifications, or comments into quoted material. Brackets are always used in pairs; you must have both an opening and a closing bracket. Do not confuse brackets [ ] with parentheses ( ).

Why does Python have two brackets?

The interior brackets are for list, and the outside brackets are indexing operator, i.e. you must use double brackets if you select two or more columns. With one column name, single pair of brackets returns a Series, while double brackets return a dataframe.


2 Answers

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.

like image 189
folkol Avatar answered Oct 29 '22 09:10

folkol


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
like image 20
Zizouz212 Avatar answered Oct 29 '22 08:10

Zizouz212