Treading on Python Volume 1: Foundations of Python by Matt Harrison

Treading on Python Volume 1: Foundations of Python by Matt Harrison

Author:Matt Harrison [Harrison, Matt]
Language: eng
Format: epub, mobi, pdf
Tags: Python Programming Language
Published: 2011-11-03T04:00:00+00:00


>>> for name in names_to_remove:

... names.remove(name)

>>> print names

['John', 'Paul']

Another option is to make a copy of the list you are iterating over. This can be done relatively painlessly using the [:] slice copy construct that is covered in the chapter on slicing:

>>> names = ['John', 'Paul', 'George',

... 'Ringo']

>>> for name in names[:]:

... if name not in ['John', 'Paul']:

... names.remove(name)

>>> print names

['John', 'Paul']

else clauses

A for loop can also have an else clause. Any code in an else block will execute if the for loop did not hit a break statement. Here is some sample code that checks if numbers in a loop were positive:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.