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

» Understanding File and Folder Permissions (POSIX) on Linux and Mac OS X (using chmod)

Linux and Mac OS X both use a -compatible type of filesystem. This has to do with the way files are accessed by their owner and others. Files and folders have permissions for 3 different types of users:Owner: this is the user who owns the file or folderGroup: this is the permissions for any user in the group that the file belongs toOthers: this is the permissions for all other users who don't fall into one of the two above categoriesFor each of these types of users, there are 3 different...

» 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...

» Understanding pointers in C/C++

Please Note: This article assumes a familiarity with C and general programming concepts including structs, variables, integer data types, and arrays. For an introduction to C, please read .One of the most difficult concepts to grasp when learning C/C++ is pointers. They are similar to pointer variables in more modern languages like Java or C#, but their usage is more subtle. A pointer is just a variable which holds the address of another variable in memory. For example, consider the integer...