Layla
Layla

Reputation: 127

Listing 2 items at once using short version of list-making python

Is there a way to list 2 items at one line using the short version of making lists.

For example I want to write something like

G3 = [(i,j) for i in Primes and j in G2 if dig_sum(i,j) == True and con_test(i,j) == True ]

Edit: I should have mentioned this gives me error of

NameError: name 'j' is not defined


here i is an int and j is tuple

My main purpose is to get something like

G = [(i,j,k),(g,h,k)...]

I know that my uppser code will give something like

G = [(i,(j,k)),(g,(h,k))...]

but I can change it later I guess.

Here is the long version

G3 = []
for i in Primes:
    for j in G2:
        if dig_sum(i,j) == True and con_test(i,j) == True:
            G3.append((i,j[0],j[1]))
print(G3)

Upvotes: 0

Views: 49

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12157

You can unpack in the tuple literal using * and switch out and for for to have a nested for loop in a list comprehension. You also don't need == True in an if block.

G3 = [(i,*j) for i in Primes for j in G2 if dig_sum(i,j) and con_test(i,j)]

n.b. this may not work in older versions of python. I'm not sure when it was introduced.

Upvotes: 3

Related Questions