[Solved] Nested for loops extending existing list


The two main concept that you see in the last line are list comprehension and nested loops. Have a look.

for understanding better what is going on, we’re going to split that line in simplier part:

TENS

for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split():
    print(tens)

OUTPUT: twenty thirty forty fifty sixty seventy eighty ninety

the previous for loop correspond to this in list comprehension:

(tens for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split())

without print, returns a generator. if you want to see the result:

print(list(tens for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split()))

ONES

numbers = ("zero one two three four five six seven eight nine".split())
for ones in numbers[0:10]:
    print(ones)

OUTPUT: zero one two three four five six seven eight nine

the previous for loop correspond to this in list comprehension:

    (ones for ones in numbers[0:10])

MERGE FOR LOOPS

we can merge them:

for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split():
    for ones in numbers[0:10]:
        print(tens + " " + ones)
OUTPUT: twenty zero
twenty one
twenty two
twenty three
twenty four
twenty five
twenty six
twenty seven
twenty eight
twenty nine
thirty zero
thirty one
thirty two
[...]

since we don’t like very much twenty zero, we are going to add a clause:

for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split():
    for ones in numbers[0:10]:
        if ones == "zero":
            print(tens)
        else:
            print(tens + " " + ones)
OUTPUT:
twenty
twenty one
twenty two
twenty three
twenty four
[...]

And this is the same behaviour with list comprehension:

(tens if ones == "zero" else (tens + " " + ones) for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split() for ones in numbers[0:10])

which returns a list (*generator) that will be extended to your numbers list.
At last, the number that you input correspond to the index of the word in the list

1

solved Nested for loops extending existing list