0

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)
Layla
  • 117
  • 2
  • 7
  • Why can't you use `G3 = [(i,j[0],j[1]) for i in Primes and j in G2 if dig_sum(i,j) and con_test(i,j)]` ? – Pieter De Clercq Aug 29 '18 at 14:52
  • 3
    "short versino of list-making" is called "list comprehension." That terminology might help you find what you're looking for in a google search. If not, here's a shortcut: https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list – en_Knight Aug 29 '18 at 14:52
  • `for i in Primes and j in G2` is not valid Python. Read up on how to do it properly using the link above. – Denziloe Aug 29 '18 at 14:56

1 Answers1

3

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.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • re: "not sure when it was introdcued": at least a long time ago: https://www.python.org/dev/peps/pep-0448/ – en_Knight Aug 29 '18 at 14:54
  • Python 3.5 wasn't that long ago :) – FHTMitchell Aug 29 '18 at 14:54
  • The statement "You also don't need `== True` in an `if` block" is true in many contexts, but given that we know little about `dig_sum` and `con_test`, it is rather bold. `if x:` and `if x == True:` test very different things. – user2390182 Aug 29 '18 at 15:03
  • @schwobaseggl true, but I think it's fair to assume this is a beginners mistake and not a type check. – FHTMitchell Aug 29 '18 at 15:06