For Loop Python
For Loop Python
nums = []
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
for x in range(21):
if x%2 == 0:
nums.append(x)
print(nums)
Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
List comprehension with string lists
Output
['Ram', 'Mohan']
List Comprehension using Nested Loops
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
nums=[(x,y) for x in nums1 for y in nums2]
print(nums)
Output
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
List Comprehension with Multiple if Conditions
Output
[0, 10, 20]
List Comprehension with if-else Condition
EXAMPLE 1
odd_even_list = ["Even" if i%2==0 else "Odd" for i in range(5)]
print(odd_even_list)
Output
['Even', 'Odd', 'Even', 'Odd', 'Even']
List Comprehension with if-else Condition
EXAMPLE 2
odd_even_list = [str(i) + '=Even' if i%2==0 else str(i) + "=Odd" for i in range(5)]
print(odd_even_list)
Output
['0=Even', '1=Odd', '2=Even', '3=Odd', '4=Even']
ZIP Function in Python
The zip() function returns a zip object, which is an iterator of tuples
where the first item in each passed iterator is paired together,
and then the second item in each passed iterator are paired together
etc.
EXAMPLE: if we have two lists with same length, and we want to loop through
them, we could do as the following example using the zip function: