Python is an interesting language in a sense that it is one of the few languages which does not implement C-style for loop. In this sense it is similar to Pascal.
Instead of for look Python language designed propose to use range function. Python provides built-in functions range
(and, in v2,
xrange
) to generate integer sequences. The simplest way to loop n
times in Python is:
for i in range(n):
statement(s)
Generally Python stresses the importance of implicit iteration over collections, which is noble goal, which is mired by disign blunder like exclusion of C-style for loop.
All Python loops can include an else
clause, and
break
and continue
statements. The break
and
continue
statements are identical to C. While
we’re looking at oddballs, we will also study the loop else
clause here because it is intertwined with break
, and
Python’s empty placeholder statement, pass
(which is not
tied to loops per se, but falls into the general category of simple
one-word statements). In Python:
break
continue
pass
Loop else block
break
)The while
statement repeats execution of a statement or block of statements, controlled by a conditional expression.
There are no suprises here:
while
expression
:
statement
(
s
)
A while
statement can also include an else
clause, and
break
and continue
statements. Here's a very simple example:
count
=
0
while
x
>
0
:
x
//=
2
# truncating division
count
+=
1
(
'The approximate log2 is'
,
count
)
A loop within a function's body also ends if the loop body executes
a return
statement, since in this case the whole function ends.
The for
statement repeats execution of a statement, or block of statements, controlled by an iterable expression. Here's
the syntax of the for
statement:
for
target
in
iterable
:
statement
(
s
)
The in
keyword is part of the syntax of the for
statement; its purpose here is distinct from the
in
operator, which tests membership.
You can iterate over stings:
for
letter
in
'abba':
(
'give me a'
,
letter
,
'...'
)
You can also have a target with multiple identifiers, like in an unpacking assignment. In this case, the iterator's items must be
iterables, each with exactly as many items as there are identifiers in the target (in v3 only, precisely one of the identifiers can
be preceded by a star, in which case the starred item is bound to a list of all items, if any, that were not assigned to other targets).
For example, when d
is a dictionary, this is a typical way to loop on the items (key/value pairs) in d
:
for
key
,
value
in
d
.
items
():
if
key
and
value
:
# print only true keys and values
(
key
,
value
)
The items
method returns a list (in v2; another kind of iterable, in v3) of key/value pairs, so we use a for
loop with two identifiers in the target to unpack each item into key
and value
. Although components of a target
are commonly identifiers, values can be bound to any acceptable LHS expression as covered in "Assignment Statements":
prototype
=
[
1
,
'placemarker'
,
3
]
for
prototype
[
1
]
in
'xyz'
:
(
prototype
)
# prints
[1, 'x', 3]
, then
[1, 'y', 3]
, then
[1, 'z', 3]
When an iterable has a mutable underlying object, don't alter that object during a for
loop on it. For example, the
preceding key/value printing example cannot alter d
in v3 (and couldn't in v2 if it used iteritems
instead
of items
). iteritems
in v2 (and items
in v3) return iterables whose underlying object is
d
, so the loop body cannot mutate the set of keys in d
(e.g., by executing del d[key]
).
d.items()
in v2 (and list(d.items())
in v3) return new, independent lists, so that d
is not the underlying
object of the iterable; therefore, the loop body could mutate d
. Specifically:
The control target variable(s) may be rebound in the loop body, but get rebound again to the next item in the iterator at the next
iteration of the loop. The loop body does not execute at all if the iterator yields no items. In this case, the control variable is
not bound or rebound in any way by the for
statement. However, if the iterator yields at least one item, then, when the
loop statement terminates, the control variable remains bound to the last value to which the loop statement has bound it. The following
code is therefore correct only when someseq
is not empty:
for
x
in
someseq
:
process
(
x
)
(
'Last item processed was'
,
x
)
An iterator is an object i
such that you can call next(i)
. next(i)
returns the next item of
iterator i
or, when iterator i
has no more items, raises a StopIteration
exception.
Alternatively,
you can call next(i, default)
, in which case, when iterator i
has no more items, the call returns default
.
When you write a class (see "Classes and Instances"), you can allow instances of the class to be iterators by defining a special
method __next__
(in v2 the method must be called next
-this was eventually seen as a design error) that takes
no argument except self
, and returns the next item or raises StopIteration
. Most iterators are built by implicit
or explicit calls to built-in function iter
, covered in Table 7-2. Calling a generator also returns an iterator, as we'll
discuss in "Generators".
The for
statement implicitly calls iter
to get an iterator. The statement:
for
x
in
c
:
statement
(
s
)
is exactly equivalent to:
_temporary_iterator
=
iter
(
c
)
while
True
:
try
:
x
=
next
(
_temporary_iterator
)
except
StopIteration
:
break
statement
(
s
)
where _temporary_iterator
is an arbitrary name not used elsewhere in the current scope.
Thus, when iter(
c
)
returns an iterator i
such that next(i)
never
raises StopIteration
(an unbounded iterator), the loop for
x
in
c
never
terminates (unless the statements in the loop body include suitable break
or return
statements, or raise or
propagate exceptions). iter(
c
)
, in turn, calls special method c
.__iter__()
to obtain and return an iterator on c
. We'll talk more about the special method __iter__
in "Container methods".
Many of the best ways to build and manipulate iterators are found in the standard library module itertools
, covered
in "The itertools Module".
Looping over a sequence of integers is a common task, so Python provides built-in functions range
(and, in v2,
xrange
) to generate integer sequences. The simplest way to loop n
times in Python is:
for
i
in
range
(
n
):
statement
(
s
)
In v2, range(
x
)
returns a list whose items are consecutive integers from 0
(included)
up to x
(excluded). range(
x
,
y
)
returns a list whose items
are consecutive integers from x
(included) up to y
(excluded). The result is the empty list when x
is greater than or equal to y
. range(
x
,
y
,
stride
)
returns a list of integers from x
(included) up to y
(excluded), such that the difference between each two
adjacent items is stride
. If stride
is less than 0
, range
counts down from
x
to y
. range
returns the empty list when x
is greater than or equal to y
and stride
is greater than 0
, or when x
is less than or equal to y
and stride
is less than 0
. When stride
equals 0
, range
raises an exception.
While range
, in v2, returns a normal list object, usable for any purpose, xrange
(v2 only) returns a special-purpose
object, intended just for use in iterations like the for
statement shown previously (xrange
itself does not
return an iterator; however, you can easily obtain such an iterator, should you need one, by calling iter(xrange(...))
).
The special-purpose object returned by xrange
consumes less memory (for wide ranges, much less memory) than the list object
range
returns; apart from such memory issues, you can use range
wherever you could use xrange
,
but not vice versa. For example, in v2:
>>>
(
range
(
1
,
5
))
[
1
,
2
,
3
,
4
]
>>>
(
xrange
(
1
,
5
))
xrange
(
1
,
5
)
Here, range
returns a perfectly ordinary list, which displays quite normally, but xrange
returns a special-purpose
object, which displays in its own special way.
In v3, there is no xrange
, and range
works similarly to v2's xrange
. In v3, if you need a
list
that's an arithmetic progression of int
s, call list(range(...))
.
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
Google matched content |
Society
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
Quotes
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Bulletin:
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
History:
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
Classic books:
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D
Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
|
You can use PayPal to to buy a cup of coffee for authors of this site |
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.
Last modified: November 15, 2019