top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']
How would i iterate over top_imdb_movies to display the following ordered list:
1.The Shawshank Redemption
2.The Godfather
3.The Dark Knight
top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']
How would i iterate over top_imdb_movies to display the following ordered list:
1.The Shawshank Redemption
2.The Godfather
3.The Dark Knight
top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']
movie_number=0
for movie_number, movie in enumerate(top_imdb_movies):
print(f"{movie_number + 1}. {movie}")
output
1. The Shawshank Redemption
2. The Godfather
3. The Dark Knight
Use enumerate with a start value of 1 as follows:
top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']
for i, movie in enumerate(top_imdb_movies, 1):
print(f'{i}. {movie}')
Output:
1. The Shawshank Redemption
2. The Godfather
3. The Dark Knight
top_imdb_movies = ['1. The Shawshank Redemption', '2. The Godfather', '3. The Dark Knight']
for i in top_imbd_movies:
print(i)
By composing functions:
top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']
print(*map('{}.{}'.format, range(1, 1+len(top_imdb_movies)), top_imdb_movies), sep='\n')
Added the sep='\n' parameter to print and expanding the iterable object with * to avoid the for-loop
If the list is long you can define a template string as a variable to gather better performance, template = '{}.{}'
template = '{}.{}'
print(*map(template.format, range(1, 1+len(top_imdb_movies)), top_imdb_movies), sep='\n')