2.1. Exercises

Repeated Iterations Questions

sentence = ['Once', 'upon', 'a', 'time']
word_length = list()
for name in sentence: 
word_length.append(len(name))
sentence = ['Once', 'upon', 'a', 'time']
word_length = list()
name in sentence: 
  word_length.append(len(name))
sentence = ['Once', 'upon', 'a', 'time']
word_length = list()
for name in sentence: 
    word_length.append(len(name))
sentence = ['Once', 'upon', 'a', 'time']
word_length = list()
for name in sentence
    word_length.append(len(name))

Practice Iterating Over a Collection

Instructions:
Running a coding exercise for the first time could take a bit of time for everything to load. Be patient, it could take a few minutes.

When you see ____ in a coding exercise, replace it with what you assume to be the correct code. Run it and see if you obtain the desired output. Submit your code to validate if you were correct.

Make sure you remove the hash (#) symbol in the coding portions of this question. We have commented them so that the line won’t execute and you can test your code after each step.

We’ve learned about iterating , now it’s time to apply this! We have a list that contains all elements of type float. We want to create a new list that casts each element to type int.

Tasks:

  • Create a new empty list named integer_list.
  • Iterate over all the items in float_list. Cast the element to data type int and append it to integer_list.
  • Display the value of integer_list.
Hint 1
  • Are you starting your loop with for and using a colon for the first line?
  • Are you indenting each line of code in the loop?
  • Are you appending the int value to the new list with integer_list.append(int('variable-name-chose'))
Fully worked solution: