-1
A = [1,3,5]
B = ['a','b']
for x in A , for y in B :
  print(x,y)

how we can implement two for loop and can convert 2D list in 1D list

desired output : [(1,'a') ,(2,'b') ,(3,'a') ,(3,'b') ,(5,'a'),(5,'b') ]

sachin
  • 9
  • 1

3 Answers3

0

If you just want to iterate through two lists simultaneously you can use zip:

x = [1, 3, 5]
y = ['a', 'b', 'c']
for i, j in zip(x, y):
    print(i, j)  # Will print "1 a" followed by "3 b"

Note that zip will actually return a list of tuples containing the combined elements from both lists, and if the lists are not equal in length then the longer list will just be truncated

Michael
  • 2,344
  • 6
  • 12
  • That's one interpretation - but then the OP did ask for `2` for loops. If you want less for loops: `print(*zip(x,y), sep="\n")` works too – John La Rooy Nov 16 '18 at 06:40
0

If you want equal distribution of elements in both lists:

A = [1,3,5]
B = ['a','b']

l = []

for x in A:
    for y in B:
        l.extend([x, y])                

>>> print(l)
[1, 'a', 1, 'b', 3, 'a', 3, 'b', 5, 'a', 5, 'b']
  • its giving [[1, 'a']] [[1, 'a'], [1, 'b']] [[1, 'a'], [1, 'b'], [3, 'a']] [[1, 'a'], [1, 'b'], [3, 'a'], [3, 'b']] [[1, 'a'], [1, 'b'], [3, 'a'], [3, 'b'], [5, 'a']] [[1, 'a'], [1, 'b'], [3, 'a'], [3, 'b'], [5, 'a'], [5, 'b']] – sachin Nov 16 '18 at 07:05
  • I can't reproduce that output from the given inputs, please test/edit here to show inputs how you get that output https://repl.it/@downshift/TurboFatalDatabases – chickity china chinese chicken Nov 16 '18 at 07:08
0
A = [1,3,5]
B = ['a','b']

l = []
#for each element in A
for i in A:
    #for each element in B
    for o in B:
        l.append((i,o))

Iterate through each element in each list then append them together

Cua
  • 129
  • 9