-2

Please explain why this code can lead this output..

First of all:

str1 = 'AB'
str2 = '34'

The code is:

[y + x for y in str1 for x in str2]

And output is:

['A3', 'A4', 'B3', 'B4']

I don't understand why this code can lead this output.

Karl
  • 1,664
  • 2
  • 12
  • 19
Trey
  • 31
  • 8
  • 2
    Could you maybe tell us which programming language this is and improve the title a bit to make your question easier to find? Thank you :-). – David Walschots Sep 03 '18 at 21:57

1 Answers1

1

The code is the same as running two nested for loops and inserting each iteration (x + y) to the list. In your example it would be expanded to look like this:

str1 = 'AB' 
str2 = '34'

list = []  # Initialize empty list
for y in str1:  # Loop through each character in str1
    for x in str2:  # Loop through each character in str2
        list.append[y + x]  # Add character y and character x to the list

print(list)  # Shows the output of this list
Karl
  • 1,664
  • 2
  • 12
  • 19