Python 3


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)

PAGE 1 / 3
The for and while Statements
Home >>> Online Lessons, Python 3

The General Form of for

We previously studied strings and lists, and now it is time to navigate through their elements. We will use for, which has the general form as shown below:

for variable in data_collection:

We can read it as: for each element in the collection, held by variable, perform a set of subordinate processing instructions.

Note. Strings are not collections of data, but they can be iterated with for.


Below, we display in turn all the elements of a list and then all the characters of a string:
Editor -
Console/Output done

In the first case, the print statement within the for loop was executed 5 times, once for each element of the list:

Run the simulation

At each step, the variable x is assigned the next element to be used within the set of instructions.

The string str_1 has a length of 17, so the for loop was repeated that many times...


The data types str and list are iterable. For example, the type int is not iterable, so we cannot use for to access its digits, because they are not elements - it is stored in memory as a numeric value:

Proceed to the next page.
 home   list  CONTENTS   perm_identity   arrow_upward