12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Note that this example is easier to code if we employ the in operator to test membership.Because in implicitly scans a list looking for a match, it replaces the inner loop:>>> for key in tests: # For all keys... if key in items: # Let <strong>Python</strong> check for a match... print key, "was found"... else:... print key, "not found!"...(4, 5) was found3.14 not found!In general, it’s a good idea to let <strong>Python</strong> do as much of the work as possible, as inthis solution, for the sake of brevity and performance.The next example performs a typical data-structure task with a for—collecting commonitems in two sequences (strings). It’s roughly a simple set intersection routine;after the loop runs, res refers to a list that contains all the items found in seq1 andseq2:>>> seq1 = "spam">>> seq2 = "scam">>>>>> res = [] # Start empty>>> for x in seq1: # Scan first sequence... if x in seq2: # Common item?... res.append(x) # Add to result end...>>> res['s', 'a', 'm']Unfortunately, this code is equipped to work only on two specific variables: seq1 andseq2. It would be nice if this loop could somehow be generalized into a tool youcould use more than once. As you’ll see, that simple idea leads us to functions, thetopic of the next part of the book.Iterators: A First LookIn the prior section, I mentioned that the for loop can work on any sequence type in<strong>Python</strong>, including lists, tuples, and strings, like this:>>> for x in [1, 2, 3, 4]: print x ** 2,...1 4 9 16>>> for x in (1, 2, 3, 4): print x ** 3,...1 8 27 64>>> for x in 'spam': print x * 2,...ss pp aa mm258 | Chapter 13: while and for Loops

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!