-2

I'm new to Python.

I stumped upon with one of this comprehension

print([[i+j for i in "abc"] for j in "def"])

Could you please help me convert the comprehension in for loop?

I'm not getting the desired result by for loop:

list = []
list2 = []

for j in 'def':
    for i in 'abc':
        list.append(i+j)
    list2 = list
print (list)

the above is my try with for loop. I' missing something. Below should be the desired result in for loop that i want.

([[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’, ‘bf’, ‘cf’]])

which I believe is a matrice.

Thanks in advance.

Abhishek Kedia
  • 787
  • 4
  • 17
Sunil
  • 3
  • 2

3 Answers3

4

The easiest thing to unravel a comprehension like this is to take it one comprehension at a time and write that as a loop. So:

[[i+j for i in "abc"] for j in "def"]

becomes:

outer_list = []
for j in "def":
    outer_list.append([i + j for i in "abc"])

Alright, cool. Now we've gotten rid of the outer comprehension so we can unravel the inner comprehension next:

outer_list = []
for j in "def":
    inner_list = []
    for i in "abc":
        inner_list.append(i + j)
    outer_list.append(inner_list)
mgilson
  • 264,617
  • 51
  • 541
  • 636
1

For loop for this comprehension will look like this

result = []
for j in "def":
    r = []
    for i in "abc":
        r.append(i+j)
    result.append(r)
Sardorbek Imomaliev
  • 12,796
  • 2
  • 39
  • 50
1
a = 'abc'
b = 'def'

>>> [[x+y for x in a]for y in b]
[['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']]

Loop

>>> for y in b:
...     for x in a:
...         print x+y,
... 
ad bd cd ae be ce af bf cf
Tzury Bar Yochay
  • 8,066
  • 4
  • 44
  • 70