enumerate( iterable )
Printing List via for-loop
>>> my_alphabet_list = list('abcdefghijklmnopqrstuvwxyz')
>>> count = 0
>>> for letter in my_alphabet_list:
... print('{}: {}'.format(count, letter))
... count += 1
...
a,b,c,d, ... ,z
enumerate( )
It’s a function that uses the for loop to iterate through an iterable, using a Tuple of 2 items: index and value of the iterable.
>>> for index, letter in enumerate(my_alphabet_list): ... print('{}: {}'.format(index, letter)) ... a,b,c,d, ... ,z
Here, step is a packed Tuple.
>>> for step in enumerate(my_alphabet_list): ... print('{}: {}'.format(step[0], step[1])) ... a,b,c,d, ... ,z
Unpacking Operators * and **
* for Tuples & Lists , ** for Dictionaries
>>> for step in enumerate(my_alphabet_list): ... print('{}: {}'.format(*step)) ... a,b,c,d, ... ,z
dict.items( )
Similar to enumerate( ), Dictionaries have items( ).
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items( ) method.
>>> my_dict = {'name': 'Kenneth', 'job': 'Teacher', 'employer': 'Treehouse'}
>>> for key, value in my_dict.items()
... print('{}: {}'.format(key.title(), value))
...
Name: Kenneth
Employer: Treehouse
Job: Teacher
EXERCISE
Create a function that takes 2 iterables and returns a list of tuples, where each item of each iterable is combined in those tuples.
def combo(iterable1, iterable2):
my_tuple = []
for index, item in enumerate(iterable1):
my_tuple.append( (iterable1[index], iterable2[index]) )
return my_tuple
my_alphabet = list("abcdefghijklmnopqrstuvwxyz")
my_numbers = list("12345678901234567890123456")
print(combo(my_numbers, my_alphabet))
Output:
[('1', 'a'), ('2', 'b'), ('3', 'c'), ..., ('6', 'z')]