0

In this example:

sorted_data = [files.data[ind] for ind in sort_inds] 

May someone please provide an explanation as to how the expression behind the for loop is related or how it is working, thanks.

3
  • 5
    Read on list compression Commented Oct 17, 2013 at 22:57
  • 6
    I think @karthikr means list comprehension docs.python.org/2/tutorial/… Commented Oct 17, 2013 at 23:00
  • Please don't downvote a question just because you already know the answer. I spent quite a while googling for this, merely because I didn't know the name for it. Seeing the expression precede the for-in definitely made me scratch my head, having never seen a list comprehension expressed this way. Commented Mar 1, 2015 at 2:02

3 Answers 3

4

It's called a List Comprehension

In other words

sorted_data = [files.data[ind] for ind in sort_inds] 

is equivalent to:

sorted_data = [] for ind in sort_inds: sorted_data.append(files.data[ind]) 

It's just a lot more readable using the comprehension

Sign up to request clarification or add additional context in comments.

Comments

2

ok so here is a simple example:

say i have a list of ints:

nums = [1,2,3] 

and i do this:

[i**2 for i in nums] 

it will output:

[1, 4, 9] 

this is equivalent to this: for i in nums: list.append(i**2)

because it iterated through the list and squared each item in the list

another example:

say i have a list of strings like this:

list1 = ['hey, jim','hey, pam', 'hey dwight'] 

and I do this:

[phrase.split(',') for phrase in list1] 

this will output this list:

[['hey', ' jim'], ['hey', ' pam'], ['hey dwight']] 

this is equivalent too:

for phrase in list1: new_phrase = phrase.split(',') list.append(new_phrase) 

it went through and made a list out of each item but it used split on each item

its basically a compacted for loop and instead of using append() it just creates the list!. it is much more readable and takes less lines

learn more here

Comments

0

It means for every item in this case ind present in sort_inds, pass it as a parameter to the function files.data[ind].

Save the result in a list (sorted_data)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.