delViento
delViento

Reputation: 167

How to output multiple lists while looping through other input lists?

For the following 2 input lists, I want different output lists based on the first one:

al = ["tr1", "tr2", "tr3"]
bl = ["tile1", "tile2", "tile3"]
newlist  = []

for a in al:
    for b in bl:
        c = a+b+"5"
        newlist.append(c)
print(newlist)

['tr1tile15', 'tr1tile25', 'tr1tile35', 'tr2tile15', 'tr2tile25', 'tr2tile35', 'tr3tile15', 'tr3tile25', 'tr3tile35']

Desired output:

newlist_tr1 = ['tr1tile15', 'tr1tile25', 'tr1tile35']
newlist_tr2 = ['tr2tile15', 'tr2tile25', 'tr2tile35']
newlist_tr3 = ['tr3tile15', 'tr3tile25', 'tr3tile35']

Working on Windows 10, Python 3.7.6.

Upvotes: 0

Views: 59

Answers (4)

Ajay
Ajay

Reputation: 5347

from itertools import product

m=["".join(elem)+'5' for elem in list(product(al,bl))]

for i in al:
    newlist_i =m[:len(al)]

product(A, B) returns the same as ((x,y) for x in A for y in B).

Upvotes: 0

azro
azro

Reputation: 54168

You need an intermediate list in the loop

al = ["tr1", "tr2", "tr3"]
bl = ["tile1", "tile2", "tile3"]
newlist = []

for a in al:
    tmp = []
    for b in bl:
        tmp.append(a + b + "5")
    newlist.append(tmp)

print(newlist) 
# [['tr1tile15', 'tr1tile25', 'tr1tile35'], 
   ['tr2tile15', 'tr2tile25', 'tr2tile35'], 
   ['tr3tile15', 'tr3tile25', 'tr3tile35']]

You can achieve the same with lists-comprehension

newlist = [[a + b + "5" for b in bl] for a in al]

Upvotes: 2

Mahesh
Mahesh

Reputation: 41

bl = ["tile1", "tile2", "tile3"]
newlist  = []


for a in al:
    for b in bl:
        c = a+b+"5"
        newlist.append(c)
    print(newlist)
    newlist  = []

['tr1tile15', 'tr1tile25', 'tr1tile35']
['tr2tile15', 'tr2tile25', 'tr2tile35']
['tr3tile15', 'tr3tile25', 'tr3tile35']```

Upvotes: 0

Stephan Kulla
Stephan Kulla

Reputation: 5077

al = ["tr1", "tr2", "tr3"]
bl = ["tile1", "tile2", "tile3"]

newlist = [[a + b + "5" for b in bl] for a in al]

Result:

[['tr1tile15', 'tr1tile25', 'tr1tile35'],
 ['tr2tile15', 'tr2tile25', 'tr2tile35'],
 ['tr3tile15', 'tr3tile25', 'tr3tile35']]

Upvotes: 0

Related Questions