Alanrlopez
Alanrlopez

Reputation: 83

Assign a Variable to a Loop in Python

for names in city_names:
    iteration_count += 1
    print(iteration_count, names)

I am trying to set the result of this loop equal to a variable, how would I proceed in doing so?

Here is the list I am using in the loop:

city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

Upvotes: 0

Views: 62

Answers (3)

blhsing
blhsing

Reputation: 106568

In general, to capture what gets printed to the standard output into a variable, you can temporarily override sys.stdout with a StringIO object using the unittest.mock.patch method as a context manager:

from io import StringIO
from unittest.mock import patch

with patch('sys.stdout', new=StringIO()) as output:
    iteration_count = 0
    for names in city_names:
        iteration_count += 1
        print(iteration_count, names)
print(output.getvalue())

This outputs:

1 Buenos Aires
2 Toronto
3 Marakesh
4 Albuquerque
5 Los Cabos
6 Greenville
7 Archipelago Sea
8 Pyeongchang
9 Walla Walla Valley
10 Salina Island
11 Solta
12 Iguazu Falls

Upvotes: 1

alyssaeliyah
alyssaeliyah

Reputation: 2244

Try this :

 city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

 result = ''
 iteration_count = 1
 for names in city_names:    
    result = result + str(iteration_count) + ' ' + names + ' '
    iteration_count += 1
 print (result)

Result is as you wanted it to be:

1 Buenos Aires 2 Toronto 3 Marakesh 4 Albuquerque 5 Los Cabos 6 Greenville 7 Archipelago Sea 8 Pyeongchang 9 Walla Walla Valley 10 Salina Island 11 Solta 12 Iguazu Falls 

Upvotes: 1

blhsing
blhsing

Reputation: 106568

You can use the str.join method with a generator expression that iterates through the enumerate generator that outputs city_names with a counter:

output = ''.join(f'{count} {name}\n' for count, name in enumerate(city_names, 1))

output becomes:

1 Buenos Aires
2 Toronto
3 Marakesh
4 Albuquerque
5 Los Cabos
6 Greenville
7 Archipelago Sea
8 Pyeongchang
9 Walla Walla Valley
10 Salina Island
11 Solta
12 Iguazu Falls

Upvotes: 1

Related Questions