1. Learn
  2. /
  3. Courses
  4. /
  5. Drag and Drop Examples

Connected

Exercise

(SAMPLE ITERATIVE) A taste of things to come

In this exercise, we'll explore both the Non-Pythonic and Pythonic ways of looping over a list.

names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']

Suppose we wanted to collect the names in the above list that have 6 letters or more. In other programming languages, the typical approach would be to create an index variable (i), use i to iterate over the list, and use an if statement to collect names with 6 letters or more:

i = 0
new_list= []
while i < len(names):
    if len(names[i]) >= 6:
        new_list.append(names[i])
    i += 1

Let's explore a more Pythonic way of doing this.

Instructions 1/3

undefined XP
  • 1

    Print list new_list that was created using a Non-Pythonic approach.

  • 2

    A more Pythonic approach would loop over the contents of names, rather than using an index variable. Print better_list.

  • 3

    The best Pythonic way of doing this is using list comprehension. Print best_list.