For loop inside an array?

Question:

The snippet below is supposed to take in image labels(directory consists of respective labels as file names) in the given directory and plot the image using a subplot.

import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg 

training_hor_dir='./horse-or-human/horses'
training_hum_dir='./horse-or-human/humans'
nrows=4
ncols=4

pic_index=0
fig=plt.gcf()
fig.set_size_inches(ncols*4,nrows*4)

pic_index+=8
next_horse_pic=[os.path.join(training_hor_dir,fname)
 for fname in training_hor_labels[pic_index-8:pic_index]]

Can someone please walk me through how the following for loop work? What’s the core concept behind such a snippet(join statement followed by for loop inside an array ? I can’t get my head around it)?

Also, Is it possible to add in furthermore statements after for loop? If so, how? and if not, why?

And how to print fname inside for-loop?

Any help is appreciated. Thanks in advance.

Asked By: Pam Cesar

||

Answers:

It’s called a comprehension: it’s a clever way of creating new data from data you already have. Generally it works like this:

newList = [oldValue * 2 for oldValue in oldList]

Where oldValue * 2 can be replaced with whatever operation you want.

There’s lots of other things you can do with comprehensions – too much to list here. Dictionaries, nested comprehensions, and so on. Here’s an article to get started.

As for printing (or executing any commands for that matter) technically you can just throw away the new value, like so:

uselessList = [print(item) for item in oldList]

But then the new uselessList would just be loads of Nones. What I’d do is just use another for loop and print the items out the old fashioned way.

Answered By: lancylot2004
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.