Iterating over Iterables Flashcards
In this exercise, you will reinforce your knowledge about these by iterating over and printing from iterables and iterators. You are provided with a list of strings flash. You will practice iterating over the list by using a for loop. You will also create an iterator for the list and access the values from the iterator.
what’s an iterator
An iterator is an object that contains a countable number of values and you can traverse through all the values
what are examples of iterable objects
lists, tuples, dictionaries, sets
Write a for loop to iterate through mytuple:
mytuple = (“apple”, “banana”, “cherry”)
mytuple = (“apple”, “banana”, “cherry”)
for x in mytuple:
print(x)
Iterate the characters of mystring
mystr = “banana”
mystr = “banana”
for x in mystr:
print(x)
Create a for loop to loop over flash and print the values in the list. Use person as the loop variable.
Create an iterator for the list flash and assign the result to superhero.
Print each of the items from superhero using next() 4 times.
Create a list of strings: flash
flash = [‘jay garrick’, ‘barry allen’, ‘wally west’, ‘bart allen’]
Print each list item in flash using a for loop
for person in flash:
print(person)
Create an iterator for flash: superhero
superhero = iter(flash)
Print each item from the iterator
print(next(superhero))
print(next(superhero))
print(next(superhero))
print(next(superhero))
Some info about range()
You can use range() in a for loop as if it’s a list to be iterated over:
for i in range(5):
print(i)
Reange() doesn’t actually create the list; instead, it creates a range object with an iterator that produces the values until it reaches the limit (in the example, until the value 4). If range() created the actual list, calling it with a value of
may not work, especially since a number as big as that may go over a regular computer’s memory. The value
is actually what’s called a Googol which is a 1 followed by a hundred 0s. That’s a huge number!
Your task for this exercise is to show that calling range() with 10 to the hundredth power
won’t actually pre-create the list.
Create an iterator object small_value over range(3) using the function iter().
Using a for loop, iterate over range(3), printing the value for every iteration. Use num as the loop variable.
Create an iterator object googol over range(10 ** 100)
small_value = iter(range(3))
print(next(small_value))
print(next(small_value))
print(next(small_value))
Loop over range(3) and print the values
for num in range(3):
print(num)
Create an iterator for range(10 ** 100): googol
googol = iter(range(10 ** 100))
Print the first 5 values from googol
print(next(googol))
print(next(googol))
print(next(googol))
print(next(googol))
print(next(googol))
Create a range object that would produce the values from 10 to 20 using range(). Assign the result to values.
Use the list() function to create a list of values from the range object values. Assign the result to values_list.
Use the sum() function to get the sum of the values from 10 to 20 from the range object values. Assign the result to values_sum.
Create a range object: values
values = range(10, 21)
Print the range object
print(values)
Create a list of integers: values_list
values_list = list(values)
Print values_list
print(values_list)
Get the sum of values: values_sum
values_sum = sum(values)
Print values_sum
print(values_sum)
what does enumerate() do?
enumerate() returns an enumerate object that produces a sequence of tuples, and each of the tuples is an index-value pair.
Create a list of tuples from mutants and assign the result to mutant_list. Make sure you generate the tuples using enumerate() and turn the result from it into a list using list().
Complete the first for loop by unpacking the tuples generated by calling enumerate() on mutants. Use index1 for the index and value1 for the value when unpacking the tuple.
Complete the second for loop similarly as with the first, but this time change the starting index to start from 1 by passing it in as an argument to the start parameter of enumerate(). Use index2 for the index and value2 for the value when unpacking the tuple.
Create a list of strings: mutants
mutants = [‘charles xavier’,
‘bobby drake’,
‘kurt wagner’,
‘max eisenhardt’,
‘kitty pryde’]
Create a list of tuples: mutant_list
mutant_list = list(enumerate(mutants))
Print the list of tuples
print(mutant_list)
Unpack and print the tuple pairs
for index1, value1 in enumerate(mutants):
print(index1, value1)
Change the start index
for index2, value2 in enumerate(mutants, start=1):
print(index2, value2)
Create a zip object by using zip() on mutants and powers, in that order. Assign the result to z1.
Print the tuples in z1 by unpacking them into positional arguments using the * operator in a print() call.
Because the previous print() call would have exhausted the elements in z1, recreate the zip object you defined earlier and assign the result again to z1.
‘Unzip’ the tuples in z1 by unpacking them into positional arguments using the * operator in a zip() call. Assign the results to result1 and result2, in that order.
The last print() statements prints the output of comparing result1 to mutants and result2 to powers. Click Submit Answer to see if the unpacked result1 and result2 are equivalent to mutants and powers, respectively.
Create a zip object from mutants and powers: z1
z1 = zip(mutants, powers)
Print the tuples in z1 by unpacking with *
print(*z1)
Re-create a zip object from mutants and powers: z1
z1 = zip(mutants, powers)
‘Unzip’ the tuples in z1 by unpacking with * and zip(): result1, result2
result1, result2 = zip(*z1)
Check if unpacked tuples are equivalent to original tuples
print(result1 == mutants)
print(result2 == powers)
Initialize an empty dictionary counts_dict for storing the results of processing the Twitter data.
counts_dict = {}
Iterate over the ‘tweets.csv’ file by using a for loop. Use the loop variable chunk and iterate over the call to pd.read_csv() with a chunksize of 10.
In the inner loop, iterate over the column ‘lang’ in chunk by using a for loop. Use the loop variable entry.
–Iterate over the file chunk by chunk
for chunk in pd.read_csv(‘tweets.csv’, chunksize=10):
-- Iterate over the column in DataFrame for entry in chunk['lang']: if entry in counts_dict.keys(): counts_dict[entry] += 1 else: counts_dict[entry] = 1
Define the function count_entries(), which has 3 parameters. The first parameter is csv_file for the filename, the second is c_size for the chunk size, and the last is colname for the column name.
def count_entries(csv_file, c_size, colname):
“"”some quote: Return a dictionary with counts of occurrences as value for each key.”””