For Loops in Python

(3 votes, average 5.00 out of 5)

For loops in Python are a bit different than most languages.  You may not iterate over some integer and increment as you go.  Rather, python uses for loops to iterate over lists or strings (represented as lists).  Python also does not use brackets to determine scope, but rather indentation.  Example below. 

 

1
2
3
>>> x = [1, 2, 3]
>>> for value in x:           #begin for loop, note the colon
>>>	print x               #part of the loop, indented in

 

In some cases, you want to know the where in the list the loop currently is.  For this, we can use the enumerate function.

1
2
3
4
5
6
7
>>> x = [4, 5, 6]
>>> for index, value in enumerate(x):
>>>	print index
0
1
2
>>>

Some notes about Python for-loop syntax:

  • The for line must end in a colon.  This denotes the start of the loop. 
  • Any line that is indented past the for keyword is PART of the loop.  The loop is closed by indenting to the same margin as the original for line.
  • No imports are needed for enumerate
Partner Links:
Last Updated on Tuesday, 29 June 2010 12:37  
Related Articles

» Verilog Operators

Operators in Verilog are the same as operators in programming languages. They take two values and compare or operate on them to yield a new result. Nearly all the operators in Verilog are exactly the same as the ones in the C programming language.Operator TypeOperator SymbolOperation PerformedArithmetic*Multiply/Division+Addition-Subtraction%Modulus+Unary plusiUnary minusRelational>Greater than<Less Than>=Greater than or equal to<=Less than or equal...

» How to Change Mouse Sensitivity in Windows 7

To change how sensitive your mouse is in Windows 7, navigate to the Start button in the left hand corner and click "Control Panel".  In the search box, search for "mouse".Click on the "Change mouse settings" option and navigate to the "pointer options" tab on the top.The "Select a pointer speed" bar controls how sensitive your mouse is.  Adjust it accordingly and press Apply to save the changes.

» How to use Adobe Photoshop's "Alt" Key in Ubuntu 11.10 and Later

When using Adobe Photoshop under WINE on Linux, it is necessary to be able to use the Alt key for a variety of Photoshop actions, such as selecting a source for the Clone Tool. By default, GNOME binds to the Alt key, which prevents Photoshop from being able to use it. In order to change GNOME's Alt keybinding, do the following:Open the Ubuntu Software Center and install gconf-editor (or from the command line sudo apt-get install gconf-editor)Open the Dash or a terminal and launch...