0

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.

0

4 Answers 4

2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much!!!!! How is that called? I checked in python tutorials about lists, but I couldn't find information on how to build those lists. Also, you are creating a list of lists, I guess, making complete independent lists is different
@delViento this is called list-comprehension docs.python.org/3/tutorial/… . Also you can now think about acepting the answer, green tick, if it satisfies you ;)
Thank you! I upvoted it and forgot to accept
0
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']]

Comments

0
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']```

Comments

0
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.