Single line loops

background image
Home / Learn / Programming Fundamentals /
Single line loops

In most programming languages, you can use a loop to execute a block of code multiple times. There are several types of loops, such as for loops and while loops, that allow you to specify the number of iterations or the condition for continuing the loop.

In Python, you can use the range function to create a sequence of numbers and iterate over them using a for loop. Here is an example of how to use a single line for loop in Python:

# Print the numbers from 1 to 10
for i in range(1, 11):
  print(i)

This code will print the numbers from 1 to 10 on separate lines.

You can also use a list comprehension to create a list of values and iterate over it in a single line. Here is an example of a single line list comprehension in Python:

# Create a list of squares from 1 to 10
squares = [i**2 for i in range(1, 11)]
print(squares)  # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In this example, we use a list comprehension to create a list of squares from 1 to 10. The list comprehension iterates over the numbers in the range function and calculates the square of each number.