Friday, 4 December 2015

Python: Looping over lists

Using for loop
for var in list:
         # Do processing here


You can use for loop like above to loop over a list. Following example explains this.

>>> countries=['India', 'China', 'Pakisthan', 'Sri Lanka', 'Bangladesh']
>>> for i in countries:
...     print(i)
... 
India
China
Pakisthan
Sri Lanka
Bangladesh

By using enumerate method, we can iterate over a list.

By using enumerate function
‘enumerate’ function return the position, corresponding value in the list.

>>> countries
['India', 'China', 'Pakisthan', 'Sri Lanka', 'Bangladesh']
>>> for i,v in enumerate(countries):
...     print(i, v)
... 
0 India
1 China
2 Pakisthan
3 Sri Lanka
4 Bangladesh

To loop over a sequence reversely
‘reversed’ function is used to loop over a sequence reversely.

>>> countries
['India', 'China', 'Pakisthan', 'Sri Lanka', 'Bangladesh']
>>> 
>>> for i in reversed(countries):
...     print(i)
... 
Bangladesh
Sri Lanka
Pakisthan
China
India


To loop over a sequence in sorted order
Use ‘sorted’ function to loop over a sequence in sorted order.

>>> for i in sorted(countries):
...     print(i)
... 
Bangladesh
China
India
Pakisthan
Sri Lanka


Loop over more than one list at a time
‘zip’ function is used to loop over more than one list at a time.

>>> for country, capital in zip(countries, capitals):
...     print(country, capital)
... 
India Delhi
China Beijing
Pakisthan Islamabad
Sri Lanka Sri Jayawardenepura-Kotte
Bangladesh Dhaka


Loop using index

>>> countries
['India', 'China', 'Pakisthan', 'Sri Lanka', 'Bangladesh']
>>> 
>>> for i in range(len(countries)):
...     print(countries[i])
... 
India
China
Pakisthan
Sri Lanka
Bangladesh







Previous                                                 Next                                                 Home

No comments:

Post a Comment