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.
numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
for number in numbers:
print(number)
numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
for i in range(len(numbers)):
print(numbers[i])
numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
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]