Python for loop in one line explained with easy examples

Related Searches: one liner for loop python, python one line for loop, single line for loop python, python for loop one line, python for loop in one line, how to write a for loop in one line python, python inline for loop

 

Introduction to Python for loop in one line

We know that for loop in Python is used to iterate over a sequence or other iterable objects.  For loop can be written in various different forms and one of them is for loop in one line which is very popular among Python developers. In this tutorial, we will explain the syntax and implementation of one line for loop in Python. Moreover, we will also cover different forms of one-line for loop that exists in python.

Advertisement

 

Getting start with Python for loop in one line

The simple python for loop in one line is a for loop, which iterates through a sequence or an iterable object. We can either use an iterable object with the for loop or the range() function. The iterable object can be a list, set, array or dictionary. In this section, we will cover the basic syntax of one line for loop with various different examples.

 

The simple syntax of Python for loop in one line

There is no fixed syntax of python for loop in one line. It depends on the problem and logic. First, let us see the basic syntax of simple python for loop and one line for loop and then we look at some examples as well.

Syntax of python simple for loops look like this:

for <element>  in <any_iterable>:
    for-loop statement

Let us convert this to python one line for loop which looks like the following.

for <element> in <any_iterable> : for-loop statement

 

Example-1: Python for loop in one line

Now, let us take an example of a simple for loop which prints out numbers from 1 to 10.

# simple for loop
for number in range(1, 5):

# printing number
   print(number)

Output:

Advertisement
1
2
3
4

Now let us see the syntax

# Python for loop in one line
for number in range(1, 5) : print(number)

Output:

1
2
3
4

 

Example-2: Python for loop one line with list

It seems to be very simple as we had just written a print statement along with a for loop in one line. But things get complicated with multiple for loops along with conditions which we will see later in this tutorial. For now, let us take another example of for loop which iterates over a list and prints its items.

mylist = ["b", "a", "s", "h"]

# Python for loop
for i in mylist:
   print(i)

Output:

b
a
s
h

Now let us implement the same logic in python for loop one lined.

mylist = ["b", "a", "s", "h"]

# Python for loop one lined
for i in mylist: print(i)

Output:

b
a
s
h

 

Example-3: Python for loop one line with list comprehension

Python is famous and renowned for being efficient, easy to understand, and almost as simple to read the code. One of the distinctive aspects of the language is the python list comprehension feature, which is one-line code with powerful functionalities. List comprehensions are used to create new lists from other iterables like tuples, strings, arrays, lists, etc.

A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

Advertisement

Here is the simple python syntax for list comprehension.

My_list = [<expression> <for loop> <condition if any>]

Notice that there is no comma or semicolon between expressions and for loop or for loop and conditions.

Now let us print numbers from 1 to 10 and create a new list using list comprehension. See the example below:

# creating list through list comprehension method
my_list = [number for number in range(1, 10)]

# printing newly created list
print(my_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Now let us take one more example to iterate over a list of elements and print out as a new list.

# my  list
my_list = ["b", "a", "s", "h", "i", "r"]

# iterating using list comprehension
print([element for element in my_list])

Output:

['b', 'a', 's', 'h', 'i', 'r']

Again this might seem to be very simple and easy to use and write Python for loop in one line but it becomes more complex and confusing with nested for loop and conditions. We will cover some more complex examples in the upcoming sections.

 

Python for loop in one line with if else condition

So far we have covered the very basic and simplest form of python one line for loop. Now let us take one more step and write Python for loop in one line with a condition.

Advertisement

 

Syntax to use if else condition with python for loop in one line

Here is a simple python for loop syntax with the condition.

for <element> in <any_iterable>:
    if condition:
        Statement inside condition
    else condition if any:
        statement inside else

Syntax of python one lined for loop with condition will be:

for <element> in <any_iterable>: if condition if statement else statement inside else

 

Example-1: Create list of even numbers with single line for loop

Let us say we have the following simple for loop which creates a list of only even numbers from 1 to 20. See the example below.

# created empty list
even = []
Odd = []

# simple python for loop
for number in range(1, 20):

   # condition for even number
   if number%2==0:

       # appending even number in the list
       even.append(number)

# printing the list
print(even)

Output:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Now let us print the same even number one by one without using list comprehension and use python one line for loop.

even =[]

#  python for loop in one line along with condition
for number in range(1, 20): number if number%2!=0 else even.append(number)

# printing
print(even)

Output:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Notice that we had used the if-else statement in the above python one line for loop, because if statement in one line for loop takes else by default. If we do not use the else statement, it will give us a syntax error.

Python for loop in one line explained with easy examples

 

Example-2: Create square of odd numbers using one liner for loop

Now let us take one more example of one line for loop to understand everything clearly. Let us say we have the following simple for loop which gives the square of only odd numbers from 1 to 10.

# simple for loop
for i in range(1, 10):

   # checking if number is even
   if i%2==0:
       pass
   else:

       # printing square
       print(i*i)

Output:

1
9
25
49
81

Now let us use python for loop in one line to print the square of all odd numbers from 1 to 10 using the same logic.

#  python for loop in one line along with condition
for i in range(1, 10): i if i%2==0 else print(i**2)

Output:

1
9
25
49
81
IMPORTANT NOTE:

Notice that we didn’t use the pass keyword in python one line for loop. Python one line for loop does not support keywords like pass, break and continue. If we try to use them we will get errors. It is because if is a statement, rather than an expression (which means, print is a statement, but the rest is being interpreted as an expression, which fails). Expressions have values. pass doesn't because it's a statement.

We can achieve the same result by creating a list of squares of odd numbers from 1 to 10 using list comprehension as well. See the example below.

 #  python for loop in one line along with condition
print([number**2 for number in range(1, 10) if number%2!=0])

Output:

[1, 9, 25, 49, 81]

 

Nested for loop in one line

A nested for loop is an inner for loop in the loop body of the outer loop. The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops. In a nested loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the interactions in the inner loop. For each iteration in an outer loop, the inner loop re-start and completes its execution before the outer loop can continue its next iteration.  Mostly, the nested loops are used for working with multidimensional data structures, such as printing two-dimensional arrays, iterating a list that contains nested lists, etc.

 

Syntax to use nested for loop in one line

Here is a simple syntax of python for loop.

for <element> in <any_iterable>:
    for <element2> in <any_iterable>:
        statements inside for loop

Similarly, the syntax of python nested for loop in one line looks like this:

[output first_for_loop second_for_loop]

 

Example-1: Use nested for loop in single line

Now let us see how we can use nested for loop in one line in real examples. But first, let us take an example using a simple nested loop and then we will convert the same example in one line nested for loop.

See the example below.

my_lsit =[]

# simple nested for loop
# outer loop
for num1 in range(1, 5):

   # nested loop
   # to iterate from 1 to 4
   for num2 in range(1, 5):

       # appending multiplied number
       my_lsit.append(num1*num2)

# printing
print(my_lsit)  

Output:

[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]

Now let us implement the same logic in one line for loop.

# nested for loop in one line
print([num1*num2 for num1 in range(1, 5) for num2 in range(1, 5)])

Output:

[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]

Here is another way to implement the same logic but with a difference of creating a list in each outer iteration.

# nested for loop in one line
for num1 in range(1, 5): print([num1*num2 for num2 in range(1, 5)])

Output:

[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
[4, 8, 12, 16]

 

Example-2: Use nested for loop in one line

Now, let us take one more example of using nested for loop in one line. Let's say we have two lists and we want to iterate over both of them using a nested for loop to print the sum.  See the example below:

# list of numbers
list1 = [1, 2, 3 ]
list2 = [1, 2, 3 ]

# creating empty list for output
result = []

# using nested for loop
# outer for loop
for i in list1:

   # inner for loop
  for k in list2:

   #    appending sum
      result.append(i+k)

# printing
print(result)

Output:

[2, 3, 4, 3, 4, 5, 4, 5, 6]

Let us implement the same logic using a nested for loop in one line.

# list of numbers
list1 = [1, 2, 3 ]
list2 = [1, 2, 3 ]

# using nested for loop in one line
result = [i+k for i in list1 for k in list2]

# printing
print(result)

Output:

[2, 3, 4, 3, 4, 5, 4, 5, 6]

Moreover, we can create lists of sums which each outer iterations. See the example below:

# list of numbers
list1 = [1, 2, 3 ]
list2 = [1, 2, 3 ]

# using nested for loop in one line
for i in list1: print([i+j for j in list2])

Output:

[2, 3, 4]
[3, 4, 5]
[4, 5, 6]

 

Nested for loop with if statement in one line

We can use as many for loops as we want, along with as many nested conditions we want to add in Python. First, let us take a nested for loop with a condition and then we will use Python for loop in one line to give the same output.

 

Syntax to use nested for loop with if condition in one line

Simple syntax of nested for loop with if condition looks like this:

for <element1> in <any_iterable>:
    for <element2> in <any_iterable>:
        if condition:
            statements inside if

And the syntax of python one line nested for loop with if statement will be:

[output first_for_loop second_for_loop if_statement]

 

Example-1: Use single line nested for loop and if condition

Here is an example of a nested for loop with a condition that takes each element from one list and divides it with the elements of the second list if the denominator is greater than zero, and stores the result in the third list. See the example below.

# list of numbers
list1 = [1, 2, 3, 4 ]
list2 = [-1, -2, 0 , 2]

# creating empty list for output
result = []

# using nested for loop
# outer for loop
for i in list1:

   # inner for loop
  for k in list2:

   #    condition to check if denominator is greater than 0
      if k>0:
          result.append(i/k)

# printing
print(result)

Output:

[0.5, 1.0, 1.5, 2.0]

Now let us see how we can use the same logic of nested for loop with the condition in one line. See the example below:

# list of numbers
list1 = [1, 2, 3, 4 ]
list2 = [-1, -2, 0 , 2]

# Python nested for loop in one line with a condition
print([i/k for i in list1 for k in list2 if k>0])

Output:

[0.5, 1.0, 1.5, 2.0]

Here is another way to implement a nested for loop in one line with a condition.

# list of numbers
list1 = [1, 2, 3, 4 ]
list2 = [-1, -2, 0 , 2]

# Python nested for loop in one line with a condition
for i in list1: print([i/k for k in list2 if k>0])

Output:

[0.5]
[1.0]
[1.5]
[2.0]

 

Nested for loop with multiple conditions in one line

Now let us make the scenario more complex and use nested conditions with nested for loop. First, let us apply the logic in simple nested for loop, and then we will use python for loop in one line to use the same logic.

 

Syntax to use nested for loop with multiple if condition in one line

Syntax of nested for loop with multiple conditions looks like this:

for <element> in <any_iterable>:
    outer condition:
        for <element2> in <any_iterable>:
            inner condition:
                statement inside condition

And the syntax of nested for loop with multiple conditions in one line looks like this:

[output first_for_loop second_for_loop first_if_condition second_if_condition]

 

Example-1: Use single line nested for loop with multiple if conditions

See the example below which iterates over the first list and checks if the element is even, then it iterates another list and checks if the number is greater than zero, and then adds in a new list the multiplication of both elements.

# list of numbers
list1 = [1, 2, 3, 4 ]
list2 = [-1, -2, 3 , 2]
even_multipication =[]

# nested for loop
# outer for loop
for i in list1:

   # Outer condition
   if i%2==0:

       # inner for loop
       for k in list2:

           # inner condition
           if k>0:
               even_multipication.append(k*i)

# printing
print(even_multipication)

Output:

[6, 4, 12, 8]

Now let us apply the same logic in python for loop in one line. See the example below:

# list of numbers
list1 = [1, 2, 3, 4 ]
list2 = [-1, -2, 3 , 2]

# Python one line nested for loop with nested conditions
print([i*k for i in list1 for k in list2 if i%2==0 if k>0])

Output:

[6, 4, 12, 8]

We can write the outer condition before the nested for loop as well. The result will be the same.

# list of numbers
list1 = [1, 2, 3, 4 ]
list2 = [-1, -2, 3 , 2]

# Python one line nested for loop with nested conditions
print([i*k for i in list1 if i%2==0 for k in list2 if k>0])

Output:

[6, 4, 12, 8]

 

Summary

Python for loop is used to iterate over a sequence such as string, list, tuple, or any other iterable objects such as range. We can use as many for loops as we want along with conditions. Python allows us to write for loops in one line which makes our code more readable and professional. In this tutorial, we covered how we can write python for loop in one line. We start from very basic and covered nested for loops along with nested conditions and practice python for loop in one line using some real-life examples.

 

Further Reading Section

Python for loop in one line
List comprehension
More about for loop in one line

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment