What is the name of the function before the loop for in Python?

Asked

Viewed 47 times

0

Hello I come from the language c++ and java, and I am learning python. I came across the following piece of code:

data = {'Player'    :   ['Wade', 'James', 'Kobe', 'Curry'],
    'First'     :   [10, 10, 8, 12],
    'Second'    :   [12, 8, 13, 8],
    'Third'     :   [15, 12, 8, 8],
    'Fourth'    :   [18, 20, 15, 8] }

bar_width = 0.5

bars = [i + 1 for i in range(len(data['First']))]
ticks = [i + (bar_width/2) for i in bars]

The loop for I can understand perfectly, but I didn’t understand the expression i + 1 and i + (bar_width/2) that comes before the for. I’d like to know the name of this, so I can at least start looking, or if anyone has any articles, could you share them? Thank you very much!

  • 1

    [i + 1 for i in range(len(data['First']))] can be read as [1+1, 2+1, 3+1, 4+1]. Since I go from 1 to 4 because of this instruction: for i in range(len(data['First'])) which in turn creates a range (range) of the length (Len) of the index list 'First' (which has 4 items)

  • That one article explains that well

  • Thank you very much, guys!

  • 1

    For anyone who wants to look for it, the name is list comprehension - and there are the correlates generator expression, set comprehension and dict comprehension.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.