Sunday, April 26, 2020

3 ways to loop through a list or items in python

In this article, I will work through three different ways to loop through a list object in python. In particular, I will use the list of countries that have not reported any cases of the coronavirus so far as sourced from 'Johns Hopkins University' and last update: April 20, 2020.

countries = ['Comoros', 'Kiribati', 'Lesotho', 'Marshall Islands', 'Micronesia', 'Nauru', 'North Korea', 'Palau', 'Samoa', 'Sao Tome and Principe', 'Solomon Islands', 'Tajikistan', 'Tonga', 'Turkmenistan', 'Tuvalu', 'Vanuatu']


1) Using WHILE loop:
This is not a common method of looping in Python.

i = 0
while i < len(countries):
    print(countries[i])
    i += 1
This mimic the C-style for loop in other languages such as JavaScript where an arbitrary variable (i) is set, checked, and incremented.

for (var i = 0; i < countries.length; i++) {
    console.log(countries[i]);
}



2) Using RANGE function:
This is similar to "foreach" loop in other languages, it first creates a range corresponding to the indexes in the list.

for i in range(len(countries)):
    print(countries[i])



3) Using FOR-IN the usual way:
The two methods above rely on looping over indexes. Since we are not utilizing the indexes, then we don't need to access them. So, this third method loop throgh the elements without accounting for the indexes.

for c in countries:
    print(c)
Compared to other methods above, this is the most pythonic method of looping.


No comments:

Post a Comment