Intro to Python: Lists and For Loop: 8. Repetitive Process

Solution for this exercise:
for each_list in app_data_set:
print(each_list)

Question: how did ‘each_list’ get assigned as a variable when i did not assign it?

https://app.dataquest.io/m/312/lists-and-for-loops/8/repetitive-processes

Hi @gniklived2010! Welcome to our forums :slight_smile:

That is simply the syntax a for loop uses when iterating over an iterable object.

You could use:

for xyz in app_data_set:
print(xyz)

or

for anything_at_all in app_data_set:
print(anything_at_all)

The above two would result in exactly the same outcome too!

When you write the following line:

for each_list in app_data_set:

You are telling Python to iterate over each element in that list, and as the for loop passes over each item, it should consider each element to be each_list. You can then specify interactions with this each_list variable, including things like print(each_list). These actions will then get performed over each element of that list.

The each_list variable only exists within the body of your for loop, so you can’t print it on its own (i.e. outside of your for loop) unless you assign a value to it.

1 Like

The Python for statement iterates over the members of a sequence (whatever iterable you have after the word in) in order, executing the block after : each time.

The Guts of the Python for Loop

First of all, let’s review the relevant terms:

Term Meaning
Iteration The process of looping through the objects or items in a collection
Iterable An object (or the adjective used to describe an object) that can be iterated over
Iterator The object that produces successive items or values from its associated iterable
iter() The built-in function used to obtain an iterator from an iterable

Now, consider again the simple for loop presented at the start of this tutorial:

>>> a = ['foo', 'bar', 'baz']
>>> for i in a:
...    print(i)
...
foo
bar
baz

To carry out the iteration this for loop describes, Python does the following:

  • Calls iter() to obtain an iterator for a
  • Calls next() repeatedly to obtain each item from the iterator in turn
  • Terminates the loop when next() raises the StopIteration exception

The loop body is executed once for each item next() returns, with loop variable i set to the given item for each iteration. This is where assignment of a value to your variable happens!

This sequence of events is summarized in the following diagram:

Python for loop diagram

Perhaps this seems like a lot of unnecessary monkey business, but the benefit is substantial. Python treats looping over all iterables in exactly this way, and in Python, iterables and iterators abound:

  • Many built-in and library objects are iterable.
  • There is a Standard Library module called itertools containing many functions that return iterables.
  • User-defined objects created with Python’s object-oriented capability can be made to be iterable.
  • Python features a construct called a generator that allows you to create your own iterator in a simple, straightforward way.

Hope this may help.

2 Likes

I understand for loops better now. Thanks for the replies!

I am also struggling with dictionaries / reiterations.
Is the "for __ in __: " the easiest way to find out the frequencies? or we learn the hard way first to understand the underlying concept before getting an access to coding shortcuts? Am asking also b/c I 've just learned basic SQL and Python seems like an over-complicating approach to work with lists compare to SQL.

Hey there @shovyadinov!

SQL syntax is definitely very easy to pick up, so I understand if Python seems a little unnecessarily daunting by contrast, but understand that Python, being a full-fledged programming language, offers a far broader scope of use.

You’re correct that a lot of the lessons on using dictionaries to compute list frequencies form the basis of some of what is taught later. It also serves the purpose of familiarizing you with general python syntax.

You are also correct that there are much simpler ways of generating frequencies.

One thing you could do is use the collections module:

from collections import Counter

Counter(your_list)

This builds a dictionary for you, exactly like the one you’ve been building manually!

You can also convert the list to a series object using the Pandas library, and then use the value_counts() method. This is what I’d recommend, because you’ll be using the Pandas library very frequently when it comes to working with data.

import pandas as pd

pd.Series(your_list).value_counts()

Thank you @blueberrypudding85

To be more specific about this, you can indeed print it on it’s own outside the loop, if you use it after the loop has occurred. If you use it before, it will be NameError: name 'each_list' is not defined.

This kind of looping variable “scope leakage” can offer conveniences that some programmers like, such as counting how many times the iteration occured.

for i, item in enumerate(somegenerator()):
    dostuffwith(i, item)
print('The loop executed {0} times!'.format(i+1))

Here is a good discussion: https://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/
Another article on ICPO, an important thing to know after LEGB: https://lerner.co.il/2019/09/10/legb-meet-icpo-pythons-search-strategy-for-attributes/

2 Likes

Yep, I stand corrected on that. You can indeed print the looping variable after the for loop, and have it continue to maintain the last value of whatever object it was it iterated over.

E.g.

list_1 = [1,2,3,4,5,6,7]

for each_num in list_1:
    print(each_num)

Output:

1
2
3
4
5
6
7 

And then afterwards you can do the following, to check its output:

each_num + 3

Output:

10