I am new to Python.
Start with: bins = [.05, .1, .2, 1.0, -.35, .07, .1]
.
How can I compress the following code into a single line in Python? It seems that it should be possible, but I get an error when I try it. Note: I do not want to define a multi-line function elsewhere and then apply it here - that is just hiding multiple lines of code under the hood.
bins_2 = [x for x in bins if x >= 0] # Retain only nonnegative reals.
bins_2.insert(0, 0.0) # Insert 0.0 to the beginning of the list
bins_2 = list(dict.fromkeys(bins_2)) # Dedup the list
bins_2.sort() # Sort bins into ascending order using the standard ordering of the integers
The output should be: bins_2 = [0.0, 0.05, 0.07, 0.1, 0.2, 1.0]
.
It is not so much that I am opposed to having multiple lines of code (which can aid with clarity). However, I think that if I could figure out how to compress this code into a single line, then I would better understand what is happening with the related functions in the language in general. I also would like to be conscientious of run-time, so I would prefer to start with or append [0.0], read through bins and filter out negatives, deduplicate the list, and then sort it in the most-efficient order.
I think that the issue is related to the problem which underlies this question: Why does list.append() return None?
For the beginning, I tried: bins_2 = [0.0].extend([x for x in bins if x >= 0])
.
I also tried:
bins_2 = (list(dict.fromkeys(bins.insert(0, 0.0)))).sort()
bins_2 = [x for x in bins_2 if x >= 0]
Both failed. I think that this is due to the fact that functions like insert()
and sort()
modify the list to which they are applied and therefore should not be saved to another (or the same-named) variable.