Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"[float(n)-50 for n in range(100)]" - what does this do?

Tags:

python

I stumbled upon this one-liner:

[float(n)-50 for n in range(100)]

Could somebody tell me what it does? It's supposed to return a float value for a vector.

Best, Marius

like image 511
wishi Avatar asked Feb 20 '26 00:02

wishi


2 Answers

That's a list comprehension that reads "create a list of 100 elements such that for each element at index n, set that element equal to n-50".

like image 195
Andrew White Avatar answered Feb 21 '26 12:02

Andrew White


It's a list comprehension:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares 
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

We can obtain the same result with:

squares = [x**2 for x in range(10)]

This is also equivalent to squares = map(lambda x: x**2, range(10)), but it’s more concise and readable.

like image 39
Katriel Avatar answered Feb 21 '26 14:02

Katriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!