ID : 458
viewed : 122
Tags : PythonPython Loop
94
This tutorial will explain various methods to implement one-line for
loop in Python. There are different forms of one-line for
loop in Python; one can be a simple for
loop that iterates through an iterable object or a sequence. The other can be simple list comprehension and list comprehension with if ... else
statement.
for
Loop in PythonThe simple one-line for
loop is the for
loop, which iterates through a sequence or an iterable object. Therefore we can either use an iterable object with the for
loop or the range()
function. The iterable object can be a list, array, set, or dictionary.
The below example code demonstrates how to implement one-line for
loop to iterate through Python’s iterable object.
myset = {'a','b','c','d','e','f','g'} mydict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7} for x in myset: print(x) for key, val in mydict.items(): print(key,val)
The range(start, stop, step)
function returns a sequence starting from the start
value and ending at the stop
value with the step size equal to the step
.
The below example code demonstrates how to use the range()
function to implement one-line for
loop in Python.
for x in range(1,99): #do something
for
LoopList comprehension is a syntactic way to create a new list from an existing list in many programming languages, including Python. We can apply any operation on each element of the list and create a new list using simple list comprehension.
The below example code demonstrates how to implement the list comprehension using the one-line for
loop in Python. The below code creates a new list by taking the square of each element of the existing list.
mylist = [6,2,8,3,1] newlist = [x**2 for x in mylist] print(newlist)
Output:
[36, 4, 64, 9, 1]
if ... else
Statement Using the One Line for
LoopList comprehension with if ... else
statement is used to apply operations on some specific elements of the existing list to create a new list or filter elements from the existing list to create a new one.
The following example codes demonstrate how to implement the list comprehension with the if
statement and with the if..else
statement in Python using the one-line for
loop.
The below example code adds the elements to the new list if it is an odd number and discards it if it is an even number.
mylist = [1,4,5,8,9,11,13,12] newlist = [x for x in mylist if x%2 == 1] print(newlist)
Output:
[1, 5, 9, 11, 13]
The below example code using the one line if ... else
list comprehension converts an odd element to an even by adding 1
to it and adds even elements to the list without performing any operation on them, and as a result, we get a new list of even numbers.
mylist = [1,4,5,8,9,11,13,12] newlist = [x+1 if x%2 == 1 else x for x in mylist] print(newlist)
Output:
[2, 4, 6, 8, 10, 12, 14, 12]