Python logo |
Ok, now let's start comprehending some lists! Say we have a list, x_list, that contains [1, 2, 3] and we want y_list to contain the value of each element of x_list squared. That is to say, we want y list to contain [1, 4, 9]. Python makes this a very easy task indeed.
We could do it the schmuck way with a for loop:
x_list = [1, 2, 3]
y_list = []
for n in x_list:
y_list.append(n * n)
print y_list
But, of course, Python supplies us mortals with List Comprehensions (a delightfully abbreviated syntax):
x_list = [1, 2, 3]
y_list = [n * n for n in x_list]
print y_list
Both versions print [1, 4, 9], but the List Comprehensions version is indisputably more elegant. One thing I fail to understand is why the developers decided to make "Comprehensions" plural, but such is life.
Wow thanks Max, that was a really helpful tutorial about list comprehensions.
ReplyDelete