0
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']

def comb(lst1, lst2):
    for i in lst1:
            new_list = []
            for j in lst2:
                new_list.append(i + '_' + j)
    return new_list
print(comb(lst1, lst2)) 

Gives me:

['c_1', 'c_2']

I am hoping to get:

['a_1', 'a_2']

['b_1', 'b_2']

['c_1', 'c_2']

Could someone please point out the mistake in my code? Thanks!

5 Answers5

6

Try this

res = [[f'{x}_{y}' for y in lst2] for x in lst1]
print(res)

Output:

[['a_1', 'a_2'], ['b_1', 'b_2'], ['c_1', 'c_2']]
deadshot
  • 8,317
  • 4
  • 15
  • 36
2

Try this:

lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']

def comb(lst1, lst2):
    finalList = []
    for i in lst1:
            new_list = []
            for j in lst2:
                new_list.append(i + '_' + j)
            finalList.append(new_list)
    return finalList
    
print(comb(lst1, lst2)) 

new_list gets empty every time first for loop is executed. So make another list to store that value before its overwritten and return that second list with all values of new_list.

thisisjaymehta
  • 584
  • 1
  • 10
  • 24
  • 1
    Better way to do this is using list comprehension. See deadshot's [answer](https://stackoverflow.com/a/63591907/8702713) for that. – thisisjaymehta Aug 26 '20 at 06:50
0

Just look where new_list = [] is. You're creating it from scratch in every loop iteration. Just move it before for.

If you just want to see 3 those elements printed, change return into print.

lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']

def comb(lst1, lst2):
    for i in lst1:
        new_list = []
        for j in lst2:
            new_list.append(i + '_' + j)
        print(new_list)
comb(lst1, lst2)
Maciałek
  • 236
  • 2
  • 7
  • 1
    If you replace the print with a return you get only the first result. You need to add each constructed list into another list that then gets returned - see https://stackoverflow.com/a/63591903/7505395 – Patrick Artner Aug 26 '20 at 06:59
  • The best solution is the one written by deadshot https://stackoverflow.com/a/63591907/10815718 . The solution with print is only direct solution of what States.the.Obvious want to get as output, – Maciałek Aug 26 '20 at 07:24
0

try this;

lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
new_list = []
for i in lst1:
    l1=[]
    for j in lst2:
        l1.append(i + '_' + j)
    new_list.append(l1)
print(new_list)
Juhi Dhameliya
  • 172
  • 2
  • 9
0
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
for e1 in lst1:
    newList = []
    for e2 in lst2:
        newList.append(e1 + "_" + e2)
    print(newList)


Output:
['a_1', 'a_2']
['b_1', 'b_2']
['c_1', 'c_2']