Is there a pythonic way to re-write the following block of code? List comprehensions?

list comprehension python
nested list comprehension python
list comprehension python for loop
python list comprehension multiple conditions
python list comprehension two lists
implement list comprehensions to produce the following lists
dictionary comprehension python
advanced list comprehension python

I am trying to do this. This is what I came up with:

X, Y, A = [x1], [y1], [(x1 + y1) % F]
for i in range(1, N):
  X.append((C * X[i-1] + D * Y[i-1] + E1) % F)
  Y.append((D * X[i-1] + C * Y[i-1] + E2) % F)
  A.append((X[i] + Y[i]) % F)

This work but as you see it's not very pythonic. I was wondering if there is a way to get the same result in a pythonic way, probably by using list comprehension(s). Thanks!

Given x, and y don't depend on A, I might be tempted to create a generator for them, and then build X, Y, and A from that (or do whatever).

def genXYA(n):
    x, y = x1, y1
    for i in range(n):
        nx, ny = (C * x + D * y + E1) % F, (D * x + C * y + E2) % F
        a = (nx + ny) % F
        yield nx, ny, a
        x, y = nx, ny


X, Y, A = map(list, zip(*genXYA(N)))

Just to explain what's happening here...

A generator is like a list, except rather than returning everything immediately, it only returns one item at a time.

The function genXYA(n) returns a generator which returns tuples (x, y, a) at every step, and stops after n things have been returned.

Now we have this generator, we can directly create the lists X, Y, and A.

Say N = 5, if you did list(genXYA(N)), you'd get

[(x2, y2, a1),
 (x3, y3, a2),
 (x4, y4, a3),
 (x5, y5, a4),
 (x6, y6, a5)]

And what you want is to separate those columns into individual named lists. You can use zip for this. zip takes a number of iterables, and creates new iterables which are the first of each, the second of each, the third of each, etc.

In order to give the right argument to zip we need to unpack the generator. That's what the * is for.

The result of zip(*genXYA(N)) is another generator, but we can see what's inside by calling list(zip(*genXYA(N))).

[(x2, x3, x4, x5, x6), # => X
 (y2, y3, y4, y5, y6), # => Y
 (a1, a2, a3, a4, a5)] # => A

So we're getting closer the end result.

When we call map(list, zip(*genXYA(N))), we're saying that for everything in that list, we want a list of each item (and a list of a tuple is a list containing everything in the tuple).

map also returns a generator, which we can then unpack into the variables we want.


The benefit of using generators is that you only calculate the next iteration when you need it, and you don't have to store all previous iterations.

For example, if you just wanted the last value of A, you could do:

for x, y, a in genXYA(N):
    pass
print(a)

(Tutorial) Python List Comprehension, Learn how to effectively use list comprehension in Python to create This tutorial will go over the following topics in list comprehension: construct list comprehensions, how you can rewrite them as for loops As you might already know, you use for loops to repeat a block of code a fixed number of times. Whenever we want to repeat a block of code for a fixed number of times, the first way of doing it is using ‘for loops’. List comprehensions are also capable of doing the same that too with a better approach than for loops, since list comprehensions are more compact.

If you have two variables, each of which should be updated using the current value of both variables, the neat solution is to use a parallel assignment.

X, Y, A = [], [], []
x, y = x1, y1
for i in range(N):
    X.append(x)
    Y.append(y)
    A.append((x + y) % F)
    # update both x and y in parallel
    x, y = (C*x + D*y + E1) % F, (D*x + C*y + E2) % F

When to Use a List Comprehension in Python – Real Python, Rewrite loops and map() calls as a list comprehension in Python; Choose In this code block, the conditional statement filters out any characters in To understand how you can use it, consider the following example. List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

Using recursion+numpy:

import numpy as np

X=np.array([[x1, y1, 1]])
A=np.array([[C, D, E1], [D, C, E2], [1,1,1]])

def myFunc(res, A, F, N):
    res[-1,2]=1
    if(N==1):
        return np.append(res, [A@res[-1]%F], axis=0)
    else:
        N-=1
        return myFunc(np.append(res, [A@res[-1]%F], axis=0), A, F, N)


X, Y=myFunc(X, A, F, N-1)[:, :2].T

A=(X+Y)%F

Sample output:

x1=1
y1=2
C, D, E1, E2, F, N=4,15,6,7,3,11

X=np.array([[x1, y1, 1]])
A=np.array([[C, D, E1], [D, C, E2], [1,1,1]])

X, Y=myFunc(X, A, F, N-1)[:, :2].T
A=(X+Y)%F

print(X)
print(Y)
print(A)
 #outputs:

[1 1 1 1 1 1 1 1 1 1 1]
[2 0 1 2 0 1 2 0 1 2 0]
[0 1 2 0 1 2 0 1 2 0 1]

List Comprehensions in Python 3, List comprehensions offer a succinct way to create lists based on looks like, we call for it to print() and receive the following output: Using our list comprehension that created the shark_letters list above, let's rewrite it as a for loop. be initialized with an empty list, as it is in the first line of our code block. There are actually two major reasons, and even a bonus one:The two major reasons are:You can produce working code quicker.Code with List Comprehensions is even easier to read (with a bit of practice).The bonus reason:ListComps have a moderate performance advantage.(Note: You may see List Comprehensions variously referred to as comprehensions

This is what I ended up writing. Since I don't need to store x and y values:

def generate_xy(x, y, n):
  yield x, y
  for _ in range(2, n+1):
    next_x = (C*x + D*y + E1) % F
    next_y = (D*x + C*y + E2) % F
    yield next_x, next_y
    x, y = next_x, next_y

A = [(x+y)%F for x, y in generate_xy(x1, y1, N)]

Python is quite the language!

List Comprehensions, Python 2.0 introduced list comprehensions and Python 3.0 comes with dictionary There is only one function call to type and no call to the cryptic lambda import os, re, sys, shutil, inspect, difflib restFiles = [os.path.join(d[0], f) for d in os.walk(". class Java: codeMarker = ".. code-block:: java\n\n" commentTag = "//" listings� This is efficient and pythonic. The idea that you should make a newline while using for loop is probably idiomatic to some other language, C, C++ e.g. But not in python. List comprehensions come fro the Haskell world of FP. So that's elegant as they come.

You can use itertools.accumulate to express this recurrence relation and generate both x's and y's in a tuple.

import itertools
# don't actually care about entries outside the first, but needs to be right length I believe
initial_array = [(x1, y1)] + list(itertools.repeat((0,0), N-1))
XY = itertools.accumulate(initial_array, lambda prev, _: ((C*prev[0]+D*prev[1]+E1)%F, (D*prev[0]+C*prev[1]+E2)%F))
A = [(x+y)% F for x, y in XY]

This should work. XY is a generator, so you also gain the benefits of not needing to store the full list in memory.

Overusing list comprehensions and generator expressions in Python , Critics of list comprehensions often say they're hard to read. Just because there is a way to write your code as a comprehension, that doesn't� List comprehensions are a third way of making lists. With this elegant approach, you could rewrite the for loop from the first example in just a single line of code: >>> squares = [ i * i for i in range ( 10 )] >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Python List Comprehensions in 5-minutes, How can you manipulate lists and iterables in Python with less lines of But browse any Python Stack Overflow question and chances are We're shopping at a math store so all we're buying is numbers. valuable they are for writing succinct and powerful Pythonic code. Towards Data Science � Follow� 1 Is there a way to get the index of an object in a list without using a loop May 9 0 Is there a pythonic way to re-write the following block of code? List comprehensions?

List Comprehensions in Python 3 for Beginners, So you're learning to code in Python, and you're starting to Here are the basics of list comprehensions, and some ways in which they It can be anything that contains a group of elements. Say we have the following list of numbers: way to incorporate complex conditional logic without having to write� List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

Python Tutorial on List Comprehension With Examples, Python list comprehension are 35% faster than FOR loop and 45% Mastering this concept would help you in two ways: It's generally a good practice as it enhances re-usability but I carry a For example, we can multiply each element of a list of integers with the next number using the following code: But what exactly is Pythonic code, and how should you remember the major pain points/avoid obvious (bad) practices? Fortunately, the Python community is blessed with a relatively simple and complete set of code style guidelines and "Pythonic" idioms. These are one of the key reasons for the high readability of Pythonic code.

Comments
  • Thank you! That's great explanation.
  • So I can't use a list comprehension here?
  • I wouldn't try to use one. That doesn't mean you can't; surely there is some way to, but why try to do everything using a list comprehension? This computation isn't naturally a comprehension, since each result depends on the previous result, rather than on the corresponding element from some sequence which is known in advance.
  • You could generate A with list comprehension, but not X and Y.