Iterable Functions w/ For Loops
We will be exploring more functions similar to range()
where they also return an iterable sequence that we can iterate through with a for loop
1. sorted()
function
sorted()
functionThe sorted()
function will return a sorted list in order from least to greatest from a sortable sequence.
For strings, they follow their ASCII table value order.
For lists, it will depend on the datatype of each item. It is recommended that all the items have the same data type in the list if you are using sorted.
The result of a
sorted()
is printable as it returns a list
# Using sorted on a string
example = 'Computer Science!'
example_sorted = sorted(example)
print('Sorted Version:', example_sorted)
for item in example_sorted:
print(' -- Current item:', item)
# Using sorted on a list of numbers but in reverse
numbers = [2,3,5,7,11,13]
for number in sorted(numbers, reverse=True):
print('Current Number:', number)
# NOTE: if reverse is not a given argument, it will be assumed as False
2. enumerate()
function
enumerate()
functionThe enumerate()
function will pair the index for each item in the given sequence argument. This allow us to do a special type of for loop that involves variable unpacking.
The result of
enumerate()
is not printable
# Using enumerate() with a list of fruits
fruits = ['Apple', 'Banana', 'Kiwi', 'Strawberry']
for i, fruit in enumerate(fruits):
print('Current index:', i)
print('Current fruit:', fruit)
if i != len(fruits) - 1:
print('--')
# enumerate() on a string
word = 'Hello'
for i, character in enumerate(word):
print(i, character)
3. reversed()
function
reversed()
functionThe reversed()
is a simple function that reverses any given sequence.
The result of
reversed()
is not printable
# Using reversed() with a list of fruits
fruits = ['Apple', 'Banana', 'Kiwi', 'Strawberry']
for fruit in reversed(fruits):
print('Current fruit:', fruit)
# Using reversed() on a string
word = 'Do geese see God?'
for character in reversed(word):
print(character)
Last updated