Is this understanding enough on the lists?

Let's say I want to create an ints list using Python, which consists of cubes of numbers from 1 to 10 only if the cube is evenly divided by four.

I wrote this working line:

 cube4 = [x ** 3 for x in range(1, 11) if (x ** 3) % 4 == 0] 

My beef with this line of code is that it computes the cube x twice. Is there still a pythonic way to write this line? Or is it as good as getting into list comprehension?


Edit - . My question is intended to focus on avoiding extraneous computing using Python functions and nuances, while keeping the code concise and readable. Although this solution could possibly have been reached by considering other questions, I wanted to be sure that I know the best answer to this question, and not just the solution that works.

+6
source share
3 answers

You can use the generator expression:

 cubed = (x ** 3 for x in range(1, 11)) cube4 = [c for c in cubed if c % 4 == 0] 

This is still repeated through range() only once, but now the expression x ** 3 evaluated only once when the generator expression is repeated. You can combine it in one line:

 cube4 = [c for c in (x ** 3 for x in range(1, 11)) if c % 4 == 0] 

but keeping the generator expression on a separate line can help in understanding (no pun intended).

Demo:

 >>> [c for c in (x ** 3 for x in range(1, 11)) if c % 4 == 0] [8, 64, 216, 512, 1000] 

Of course, mathematically speaking, for your simple example, you could just use [x ** 3 for x in range(2, 11, 2)] , but I suspect that this was not quite the purpose of your question .:-)

+16
source

A number cube is divisible by 4 if and only if the number is even. It is easy to see if you expand each number to its main factors. Therefore:

 cube4 = [x ** 3 for x in range(1, 11) if x % 2 == 0] 
+3
source

I like the single line font, but it's worth noting that there is another pythonic way to create the desired list .

 cube4 = [] for x in range(1, 11): y = x ** 3 if not y%4: cube4.append(y) 
+1
source

Source: https://habr.com/ru/post/988119/


All Articles