Python – Iterate List example

Python – Iterate List example

List is widely used data structure in Python. In this tutorial, we will be demonstrating examples to iterate list using for loop and while loop.

1) Iterate List using for loop

if __name__ == '__main__':
	numbers = [1, 2, 3, 4, 5, 6] #containing numbers
	print('List containing numbers : ')
	for number in numbers:
		print(number)

	strings = ['str1', 'str2', 'str3', 'str4'] #containing strings
	print('List containing strings : ')
	for str in strings:
		print(str)

Output

List containing numbers : 
1
2
3
4
5
6
List containing strings : 
str1
str2
str3
str4

2) Iterate List using while loop

if __name__ == '__main__':
	#using while loop
	numbers = [1, 2, 3, 4, 5, 6] #containing numbers
	i = 0
	length = len(numbers)
	print('List containing numbers : ')
	while(i < length):
		print("number[%d] : %d" %(i, numbers[i]))
		i += 1
		
		
	strings = ['str1', 'str2', 'str3', 'str4'] #containing strings
	i = 0
	length = len(strings)
	print('List containing strings : ')
	while(i < length):
		print("strings[%d] : %s" %(i, strings[i]))
		i += 1

output

List containing numbers : 
number[0] : 1
number[1] : 2
number[2] : 3
number[3] : 4
number[4] : 5
number[5] : 6
List containing strings : 
strings[0] : str1
strings[1] : str2
strings[2] : str3
strings[3] : str4

Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *