Say I want to create a list using list comprehension like:
l = [100., 50., 25., 12.5, ..., a_n]
…i.e., start with some number and generate the n "halves" from that in the same list. I might either be missing some straightforward pythonic way of doing that, or I'll simply have to rely on a good ol' for-loop. Can this be done? Thanks.
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. Without list comprehension you will have to write a for statement with a conditional test inside:
Every list comprehension in Python includes three elements: expression is the member itself, a call to a method, or any other valid expression that returns a value. In the example above, the expression i * i is the square of the member value. member is the object or value in the list or iterable.
Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Now by using nested list comprehensions same output can be generated in fewer lines of code. Lambda Expressions are nothing but shorthand representation of Python functions.
Without list comprehension you will have to write a for statement with a conditional test inside: The return value is a new list, leaving the old list unchanged. The condition is like a filter that only accepts the items that valuate to True.
How about this?
start = 2500.0
n = 50
halves = [start / 2.0**i for i in range(n)]
equal to this:
[start * 2.0**(-i) for i in range(n)]
probably less efficient in contrast to @DeepSpace's answer but a one-liner
Define a generator, and use it in the list comprehension:
def halve(n):
while n >= 1:
yield n
n /= 2
print([_ for _ in halve(100)])
>> [100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625]
Or simply convert it to a list:
print(list(halve(100)))
>> [100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625]
EDIT In case @R Nar's comment is correct:
def halve(start, n):
for _ in range(n):
yield start
start /= 2
print(list(halve(100, 3)))
>> [100, 50.0, 25.0]
print(list(halve(100, 4)))
>> [100, 50.0, 25.0, 12.5]
The following code works with int but not floats.
[100>>i for i in range(10)]
this returns:
[100, 50, 25, 12, 6, 3, 1, 0, 0, 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With