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