While studying Python, I wondered about 'num for num in range' and 'for num in range'.
They seemed similar yet had different use cases, and I needed to understand when to use each in different situations.
Here are explanations:
1. `num for num in range` (List Comprehension):
# List Comprehension Example: Creating a list with numbers from 0 to 4
my_list = [num for num in range(5)]
print(my_list)
# Output: [0, 1, 2, 3, 4]
In this example, `num for num in range` adds each number `num` generated by `range(5)` to the list, creating a new list.
2. `for num in range` (Regular `for` loop):
# Regular for loop Example: Iterating over numbers from 0 to 4 and printing them
for num in range(5):
print(num)
# Output: 0, 1, 2, 3, 4 (each number is printed on a separate line)
In this example, `for num in range` iterates over each number generated by `range(5)` and performs a specific task. Here, the task is printing each number.
Both these constructs iterate over the same `range(5)`, but the List Comprehension creates a new list, while the Regular `for` loop performs a specific task for each number.
'Issue Note' 카테고리의 다른 글
1934. Confirmation Rate (0) | 2024.04.12 |
---|---|
The count of divisors and addition (0) | 2024.04.09 |
Difference between list and [] (Python) (0) | 2024.04.02 |
DATE - [SQL} (0) | 2024.04.01 |
Exclusion of NULL values in b.customer_id column in SQL query [SQL] (0) | 2024.03.22 |