Generating a list of numbers can be a common task in Python when it comes to data processing and other similar operations. Thankfully, Python provides several simple yet powerful ways to create such a list. In this tutorial, we will learn how to generate a list of 100 numbers using Python.
1. Using Python Range Function
The simplest and most straightforward way to generate a list of 100 numbers in Python is by using the range() function. It is built into Python and allows you to generate a list of numbers within a specified range.
1 2 |
list1 = list(range(1, 101)) print(list1) |
This code would output a list of numbers from 1 to 100.
1 |
[1, 2, 3, ..., 100] |
2. Using List Comprehension
List comprehension in Python offers a more flexible and powerful way to create lists. It involves creating a new list by iterating over an existing list and applying a condition or transformation.
1 2 |
list2 = [i for i in range(1, 101)] print(list2) |
Again, this code will output a list of numbers from 1 to 100.
1 |
[1, 2, 3, ..., 100] |
3. Using a For Loop
Another way to generate a list of 100 numbers in Python involves using a for loop and the built-in append() function, which is used to add an element to a list.
1 2 3 4 |
list3 = [] for i in range(1, 101): list3.append(i) print(list3) |
As before, this generates a list of numbers from 1 to 100.
1 |
[1, 2, 3, ..., 100] |
Full code:
1 2 3 4 5 6 7 8 9 10 |
list1 = list(range(1, 101)) print(list1) list2 = [i for i in range(1, 101)] print(list2) list3 = [] for i in range(1, 101): list3.append(i) print(list3) |
Conclusion
In this tutorial, we learned three ways to generate a list of 100 numbers in Python: using the range function, using list comprehension, and using a for loop and the append function. Each of these methods can be useful depending on your specific needs and the complexity of the operations you are performing.