four-eyes
four-eyes

Reputation: 12385

Unexpected output in Python while executing simple loop

I have this rather simple loop

cities = ['Merano', 'Madrid', 'New York', 'Bangkok']
countries = ['Italy', 'Spain', 'USA']

for index, city in enumerate(cities):
    print('This is index:', index)
    print('This is city:', city)
    print('The length of the list \'cities\' is: ', len(cities))
    print(print('The length of the list \'countries\' is: ', len(countries)))
    print(countries[index])
    print(5 * '#')

I expect it to break. However, what I did not expect is this output.

This is index: 0
This is city: Merano
The length of the list 'cities' is:  4
The length of the list 'countries' is:  3
None
Italy
#####
This is index: 1
This is city: Madrid
The length of the list 'cities' is:  4
The length of the list 'countries' is:  3
None
Spain
....

Where is the none coming from? I do not print this, nor do I execute something where I'd expect this to be printed...

Upvotes: 0

Views: 65

Answers (3)

aj95
aj95

Reputation: 26

print(print('The length of the list \'countries\' is: ', len(countries)))

in the above line you are printing print functions output.

If you look at function Def it doesn't have a return type so you are getting None from the inner print() statement.

Also a remark- fix the index check for index > len(countries)

Upvotes: 1

icp
icp

Reputation: 174

you used print(print()) in print(print('The length of the list \'countries\' is: ', len(countries))) use

print('The length of the list \'countries\' is: ', len(countries))`

Upvotes: 4

AJITH
AJITH

Reputation: 1175

Because you have 2 print commands

print(print('The length of the list \'countries\' is: ', len(countries)))

Upvotes: 2

Related Questions