Python: Generate and prints a list of numbers from 1 to 10
Python Basic - 1: Exercise-115 with Solution
Write a Python program to generate and print a list of numbers from 1 to 10.
Expected output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Sample Solution:
Python Code:
# Create a range of numbers from 1 to 10 (exclusive).
nums = range(1, 10)
# Print the original list of numbers using the 'list' function.
print(list(nums))
# Convert each number in the list to a string using the 'map' function.
# Print the resulting list of strings.
print(list(map(str, nums)))
Sample Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9] ['1', '2', '3', '4', '5', '6', '7', '8', '9']
Explanation:
Here is a breakdown of the above Python code:
- Range creation:
- The code creates a range of numbers using the "range()" function. The range includes integers from 1 to 9 (10 is exclusive).
- Printing original list:
- The original list of numbers is printed using the "list" function to convert the range to a list.
- Mapping to strings:
- The map function is used to apply the "str" function to each element in the nums range.
- This converts each integer in the range to its string representation.
- Printing resulting list:
- The resulting list of strings is printed using the "list" function to convert the mapped values to a list.
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to print letters from the English alphabet from a-z and A-Z.
Next: Write a Python program to identify nonprime numbers between 1 to 100 (integers). Print the nonprime numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/basic/python-basic-1-exercise-115.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics