Looping list and List Comprehension

Looping list and List Comprehension

Instructor-svgAl-Mamun Sarkar
Apr 11 , 2021

We can iterate a list using for loop as well as while loop. And using list comprehension we can create a list in a shorter syntax. 

 

Looping List:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
for number in numbers:
    print(number)

 

 Looping List using the index:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
for i in range(len(numbers)):
    print(numbers[i])

 

  Looping List using while loop:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
i = 0
while i < len(numbers):
    print(numbers[i])
    i += 1

 

 

List Comprehension:

Syntax:

newlist = [expression for item in iterable if condition == True]

Example Create a list from another list using comprehension:

numbers = [1, 2 ,3, 4, 5, 6, 7, 8, 9]
event_numbers = [x for x in numbers if x % 2 == 0 ]
print(event_numbers)

Output:

[2, 4, 6, 8]

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram