Usefulness of one-line statements in Python [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Is using one line loops, even nested loops always a good practice in Python? I see a lot of people just love "one-liners", but to me they're hard to read sometimes, especially if we're talking about nested loops.
Moreover most of nested loops I've seen so far exceed the recommended 79 characters per line.
So I'd like to know if "one-liners" offer anything extra apart being compact? Do they use less memory maybe?

Yes, they may be easily faster, since more code may be run in C (in explicit loop all of immediate steps has to be available to interpreter, in one-liner list comprehension it does not have to). There is also overhead of .append method call, method look-up etc. In list comprehension all of that is avoided:
import timeit
def f1():
result = []
for x in range(100):
for y in range(100):
result.append(x * y)
return result
def f2():
return [x * y for y in range(100) for x in range(100)]
print('loop: ', timeit.timeit(f1, number=1000))
print('oneliner:', timeit.timeit(f2, number=1000))
Results (Python 3):
loop: 1.2545137699926272
oneliner: 0.6745600730064325

Depends on the one-liner, some can be much more efficient and very readable.
Take the case of list comprehension. Lets say you want to take all numbers from 1 to 10 and output a list of their product multiplied by 2.
Input: [1,2,3,...,9,10]
Output: [2,4,6,...,18,20]
You can do it in a for loop like so:
output = []
for i in range(1, 11):
output.append(i*2)
Or you can just use list comprehension:
[i*2 for i in range(1,11)]
You'll see the list comprehension is MUCH faster, and also quite readable.
The same can be said for dict comprehension, set comprehension and generator expressions. Also the use of map() and filter() are highly encouraged as long as it's understandable.

For discussion... they all do the same.
'a' a list comprehension... the smoking one-liner...
'b' same thing, but you can provide annotation within a list comprehension... it is still technically a one-liner
'c' the conventional approach.
If speed is a concern, I am less worried about the speed unless, I perform the same task day in day out and it takes a really long time to perform. Comparing speed when you are talking micro or nanoseconds may be of academic interest, but it will not impact the vast majority of users.
I always vote for clarity of expression over compactness of code.
a = [i**2 for i in range(20) if i > 5 and i < 10]
b = [i**2 # do this
for i in range(20) # using these
if (i > 5) and # where this and
(i < 10) # this is good
]
c = []
for i in range(20):
if (i > 5) and (i < 10):
c.append(i**2)
EDIT
The example given of producing the product of a range of numbers, is a good indicator, that the oneliner need not be the issue, but the method used to obtain the result. I will illustrate with determining the product using only 10 values... try it with 100 if you like. I will do it in full format, but could reduce everything to a oneliner if need (import excluded).
>>> import numpy as np
>>> a = np.arange(10)
>>> b = np.arange(10).reshape(10,1)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
>>> a*b
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
[ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27],
[ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36],
[ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45],
[ 0, 6, 12, 18, 24, 30, 36, 42, 48, 54],
[ 0, 7, 14, 21, 28, 35, 42, 49, 56, 63],
[ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72],
[ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81]])
or as a one-liner
>>> out = np.arange(10) * np.arange(10).reshape(10,1)
and of course there are built-in functions to do this without the full expression I have shown.
The point being made, speed isn't everything. Clarity of code AND choosing the right tools to do the job should be considered first.

Yes. This is good practice.
Usually experienced programmers use anonymous functions (see, lambda: http://www.secnetix.de/olli/Python/lambda_functions.hawk) in one-line loops and it gives better performance.

Related

Comparing lists and extracting unique values

I have two lists:
l1: 38510 entries
l2: 6384 entries
I want to extract only values, which are present in both lists.
So far that was my approach:
equals = []
for quote in l2:
for quote2 in l1:
if quote == quote2:
equals.append(quote)
len(equals)) = 4999
len(set(equals))) = 4452
First of all, I have the feeling this approach is pretty inefficient, because I am checking every value in l1 several times ..
Furthermore, it seems that I get still duplicates. Is this due to the inner-loop for l1?
Thank you!!
You can use list comprehension and the in operator.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [2, 4, 6, 8, 0]
[x for x in a if x in b]
#[2, 4, 6, 8]
You were on the right track by using sets. One of set's coolest features is that you can get the intersection between two sets. An intersection is another way to say the values that occur in both sets. You can read about it more in the docs
Here is my example:
l1_set = set(l1)
l2_set = set(l2)
equals = l1_set & l2_set
#If you really want it as a list
equals = list(equals)
print(equals)
The & operator tells python to return a new set that only has values in both sets. At the end, I went ahead and converted equals back to a list because that's what your original example wanted. You can omit that if you don't need it.
1. This is the simplest method where we haven’t used any built-in functions.
# Two lists in most simple way of showing the intersection
def intersection(list_one, list_two):
temp_list = [value for value in list_one if value in list_two]
return temp_list
# Illustrate the intersection
list_one = [4, 9, 1, 17, 11, 26, 28, 54, 69]
list_two = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(list_one, list_two))
# [123, 3, 23, 15]
2. You can use the python set() method.
# Two lists using set() method
def intersection(list_one, list_two):
return list(set(list_one) & set(list_two))
# Illustrate the intersection
list_one = [15, 13, 123, 23, 31, 10, 3, 311, 738, 25, 124, 19]
list_two = [12, 14, 1, 15, 36, 123, 23, 3, 315, 87]
print(intersection(list_one, list_two))
# [123, 3, 23, 15]
3. In this technique, we can use the built-in function called intersection() to compute the intersected list.
First, we need to use set() for a larger list then compute the intersection.
# Two lists using set() and intersection()
def intersection_list(list_one, list_two):
return list(set(list_one).intersection(list_two))
# Illustrate the intersection
list_one = [15, 13, 123, 23, 31, 10, 3, 311, 738, 25, 124, 19]
list_two = [12, 14, 1, 15, 36, 123, 23, 3, 315, 87, 978, 4, 13, 19, 20, 11]
if len(list_one) < len(list_two):
list_one, list_two = list_two, list_one
print(intersection_list(list_one, list_two))
# [3, 13, 15, 19, 23, 123]
Additional you can follow the bellow tutorials
Geeksforgeeks
docs.python.org
LearnCodingFast
Let's assume that all the entries in both of your lists are integers. If so, computing the intersection between the 2 lists would be more efficient than using list comprehension:
import timeit
l1 = [i for i in range(0, 38510)]
l2 = [i for i in range(0, 6384)]
st1 = timeit.default_timer()
# Using list comprehension
l3 = [i for i in l1 if i in l2]
ed1 = timeit.default_timer()
# Using set
st2 = timeit.default_timer()
l4 = list(set(l1) & set(l2))
ed2 = timeit.default_timer()
print(ed1-st1) # 5.7621682 secs
print(ed2-st2) # 0.004478600000000554 secs
As you have such long lists, you might want to use numpy which is specialized in providing efficient list processing for Python.
You can enjoy the fast processing with its numpy function. For your case, you can use numpy.intersect1d() to get the sorted, unique values that are in both of the input arrays, as follows:
import numpy as np
l1 = [1, 3, 5, 10, 11, 12]
l2 = [2, 3, 4, 10, 12, 14, 16, 18]
l_uniques = np.intersect1d(l1, l2)
print(l_uniques)
[ 3 10 12]
You can keep the resulting list as numpy array for further fast processing or further convert it back to Python list by:
l_uniques2 = l_uniques.tolist()

Insert a value to a sorted list via list comprehension Python

I have an assignment to add a value to a sorted list using list comprehension. I'm not allowed to import modules, only list comprehension, preferably a one liner. I'm not allowed to create functions and use them aswell.
I'm completely in the dark with this problem. Hopefully someone can help :)
Edit: I don't need to mutate the current list. In fact, I'm trying my solution right now with .pop, I need to create a new list with the element properly added, but I still can't figure out much.
try:
sorted_a.insert(next(i for i,lhs,rhs in enumerate(zip(sorted_a,sorted_a[1:])) if lhs <= value <= rhs),value)
except StopIteration:
sorted_a.append(value)
I guess ....
with your new problem statement
[x for x in sorted_a if x <= value] + [value,] + [y for y in sorted_a if y >= value]
you could certainly improve the big-O complexity
For bisecting the list, you may use bisect.bisect (for other readers referencing the answer in future) as:
>>> from bisect import bisect
>>> my_list = [2, 4, 6, 9, 10, 15, 18, 20]
>>> num = 12
>>> index = bisect(my_list, num)
>>> my_list[:index]+[num] + my_list[index:]
[2, 4, 6, 9, 10, 12, 15, 18, 20]
But since you can not import libraries, you may use sum and zip with list comprehension expression as:
>>> my_list = [2, 4, 6, 9, 10, 15, 18, 20]
>>> num = 12
>>> sum([[i, num] if i<num<j else [i] for i, j in zip(my_list,my_list[1:])], [])
[2, 4, 6, 9, 10, 12, 15, 18]

Multiple loop control variables in Python for loop

I came across a situation where I need to implement a for loop with more than one loop control variable. Basically this is what I am trying to do
Java:
for (int i=0,j=n; i<n,j>=0; i++, j--)
do my stuff
How do I do this in Python?
for i in range(0,n), j in range(n-1,-1,-1):
do my stuff
But this doesn't work. What would be the right syntax here? Also, is there a more elegant(pythonic) construct for the use-case?
For your specific example, it doesn't look like you really need separate variables in the loop definition itself. You can just iterate over the i values and construct the j values by doing n-i:
for i in range(0, n):
j = n-i
# do stuff
In general, you can't specify multiple values in the for statement if they depend on each other. Instead, use the for to iterate over some "base" value or values from which the others can be derived.
You can specify multiple values in the for loop, but they must be drawn from a single iterable:
for i, j in zip(range(0, n), range(n, 0, -1)):
# do stuff
This takes i from the first range (0 to n-1) and j from the second (n to 1). zip creates a new iterable by componentwise pairing the elements of the iterables you give it.
The thing to remember is that Python for loops are not like loops in Java/C, which have an initialize/check end condition/update structure that repeatedly modifies some persistent loop index variable. Python for loops iterate over a "stream" of values provided by a "source" iterable, grabbing one value at a time from the source. (This is similar to foreach-type constructs in some other languages.) Whatever you want to iterate over, you need to get it into an iterable before you begin the loop. In other words, every Python for loop can be thought of as roughly analogous to something like:
for (i=iterable.getNextValue(); iterable.isNotEmpty(); i=iterable.getNextValue())
You can't have the loop initialization be different from the loop update, and you can't have those be any operation other than "get the next value", and you can't have the end condition be anything other than "is the iterable exhausted". If you want to do anything like that, you have to either do it yourself inside the loop (e.g., by assigning a secondary "loop variable" as in my example, or by checking for a custom loop exit condition and breaking out), or build it into the "source" that you're iterating over.
A lot depends on iterators you want. Here's a couple of options. What they have in common is that for... in... will traverse over lists, tuples, and anything else which supports iteration. So you could loop over a list of known values or a generator which produces an arbitrary series of values. The for... in... is the same regardless.
Here's some standard python tricks:
nested loops
for i in range(10):
for j in range (10):
print i, j
This is simple and clear, but for complex iterations it may get very deeply nested. Here range is a generator, which means it produces an iteration over a series (in this case, 10 numbers - but it could be any arbitrary stream of values))
zip
for multiple iterators you can use zip() which creates an iterable object that produces a value from each of several of iterables at the same time. You can use multple assignment inside the for loop to grab pieces out of the zip
a = [1,2,3,4]
b = ['a','b','c','d']
for number, letter in zip (a, b):
print letter, ":", number
# a : 1
# b : 2
# c : 3
# d : 4
zip will stop when the first member is exhausted:
a = [1,2]
b = ['a','b','c','d']
for number, letter in zip (a, b):
print letter, ":", number
# a : 1
# b : 2
zip also uses generators:
test = zip (range(10), range(10,20))
for item in test: print item
#(0, 10)
#(1, 11)
#(2, 12)
#(3, 13)
#(4, 14)
#(5, 15)
#(6, 16)
#(7, 17)
#(8, 18)
#(9, 19)
itertools
For more complex iterations there's a lot of great tools in the itertools module This is particularly nice for things like getting all of the products or permutations of multiple iterators. It's worth checking out but I think it's more than you need
You can create a list comprehension using more than one loop control variable:
>>> n = 10
>>> stuff = [i*j for i in range(n) for j in range(n-1,-1,-1)]
>>> stuff
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, 36, 32, 28, 24, 20, 16, 12, 8, 4, 0, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0, 54, 48, 42, 36, 30, 24, 18, 12, 6, 0, 63, 56, 49, 42, 35, 28, 21, 14, 7, 0, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0, 81, 72, 63, 54, 45, 36, 27, 18, 9, 0]

Generating a list of evenly distributed numbers from range

I have seen this question been asked before but I'm looking for an answer with a twist:
Consider I have a range like 1-100 and i want to generate a list, with a specific stepsize like: numbers(1,100,5). This would return [1,25,50,75,100]. However, I would like it to return [1,100,50,25,75] or [1,100,50,75,25] Another example would be numbers(1,10,10) which would give me something similar to [1,10,5,2,7,3,8,4,9].
Is this even possible to do? The reason for this would be to be able to render image sequences without going from frame 1 to frame 2 to frame 3 and so forth. Instead I want to render the first frame, the last frame, the middle frame, the middle of the middle frame until all frames are accounted for.
Your question is kind of underspecified, but this should help you get started.
def numbers(first, last, count):
nums = [first, last]
width = last - first
while len(nums) < count:
width /= 2
stepper = first
while stepper < last:
rounded = round(stepper)
if rounded not in nums:
nums.append(rounded)
if len(nums) == count:
break
stepper += width
return nums
Then:
>>> numbers(0, 100, 5)
[0, 100, 50, 25, 75]
>>> numbers(0, 10, 10)
[0, 10, 5, 2, 8, 1, 4, 6, 9, 3, 7]
>>> numbers(0, 50, 50)
[0, 50, 25, 12, 38, 6, 19, 31, 44, 3, 9, 16, 22, 28, 34, 41, 47, 2, 5, 8, 11, 14, 17, 20, 23, 27, 30, 33, 36, 39, 42, 45, 48, 1, 4, 7, 10, 13, 15, 18, 21, 24, 26, 29, 32, 35, 37, 40, 43, 46]
The basic algorithm is as follows:
Start with a list of nums containing the two endpoints
Initialize width to the distance between the two endpoints
Then, loop:
Halve width
Step through first, first+width, first+2*width, ..., last-width, last, and add whichever among those are not already in nums to nums (so, for numbers(0, 100, 5), the first loop iteration will try 0, 50, and 100, and only add 50 since that wasn't already present; the second iteration will try 0, 25, 50, 75, and 100, and only add 25 and 75).
If we have enough numbers in nums, we're done
Return nums
Ok, so your desired frames are kind of wierd, especially as the elements in the first example aren't evenly ranged, eg. 100-75=25, 75-50=25, 50-25=25 , 25-1=24.
But, if we assume that you always want the start and end value in the frame and want the evenly spaced values pegged against the maximum value, we can do this:
def numbers(start,stop,step=1):
frame = [start]+range(y,stop,(start-stop)/(step-1))
return frame
The random module includes a shuffle() method that takes an array and shuffles it in-place.
Which means the function becomes:
from random import shuffle
def numbers(start,stop,step=1):
frame = [start]+range(y,stop,(start-stop)/(step-1))
shuffle(frame)
return frame
Giving us the following test runs:
>>> numbers(1,100,5)
[100, 50, 75, 1, 25]
>>> numbers(1,10,10)
[1, 3, 10, 9, 6, 5, 8, 4, 7, 2]
Original (but wrong) answer
The random module includes a shuffle() method that takes an array and shuffles it in-place.
For example:
from random import shuffle
def numbers(start,stop,step=1):
frame = range(start,stop,step)
shuffle(frame)
return frame
Then calling this function we get:
>>> numbers(1,100,25)
[1, 51, 26, 76]
>>> numbers(1,100,25)
[76, 26, 1, 51]
Note, that as per the range() function, the step value is repeatedly added to start such that the final array is of the form [start, start+1*step, start+2*step ... start + n*step], where start+n*step is less than stop while start+(n+1)*step is greater than stop.

Generating a simple mathematical sequence in Python

I'm new to Python and coming from a PHP background.. I'm impressed. Is there a way of getting a list of numbers from this sequence:
i^2, i^2 + i, i^2 + 2i, ..., n
i.e. if i=2 and n=30:
4, 6, 8, ..., 30
Okay, this is a really simple sequence but is what's a more general way to do this sort of thing functionally?
Maybe there's some nice functional programming way of doing this? In PHP I think I would make some function some variables and interaction but Python might be able to do it more elegantly?
Many thanks.
You can do this with range:
In [186]: i = 2; n = 30; range(i**2, n+1, i)
Out[186]: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
Python has a cool feature called List Comprehension. You can use it to do something like this:
[i*i+2*n for n in range(30) if (i*i+2*n)<=30]

Categories

Resources