Python Iterators: Part Six

One of the main differences between Python 3.0 and Python 2.X is the stronger emphasis on iterators. In addition to the iterators associated with built-in types such as files and dictionaries, the dictionary methods keys, values and items return … [Continue reading]

Python Iterators: Part Five

Another common use for list comprehensions is with files. A file object has a readlines method that loads the file into a list of line strings all at once; e.g.: >>> fp = open('simple.py') >>> lines = fp.readlines() >>> … [Continue reading]

Python Iterators: Part Four

To see a practical application of the iteration protocol, let's consider the case of the list comprehension. You can use range to change a list as you step across it; e.g.: >>> L = [1, 2, 3, 4, 5] >>> for i in … [Continue reading]

Python Iterators: Part Three

Besides files and physical sequences such as lists, other types also have useful iterators. In older versions of Python, for example, one would step through the keys of a dictionary by requesting the keys list explicitly: >>> K = … [Continue reading]

Python Iterators: Part Two (The Next Function)

In the first article in this series, we introduced Python iterators and how they can be used to streamline Python code. In this article, we will continue our look at iterators, beginning with the next function. To support manual iteration code, … [Continue reading]

Python Iterators: Part One

Python iterator

Now that we have completed our look at strings, we will begin to look at another useful object: Python iterators. The for loop is often used when we have to iterate over a series of numbers; for example: >>> for x in … [Continue reading]

Python Strings: Part Six

In the previous article, we began our look at indexing and slicing. In this article, we will continue our look at slicing and show some practical applications of slicing. In Python 2.3 and later, there is support for a third index, used as a … [Continue reading]

Python Strings: Part Five

Because strings are defined as ordered collections of characters, we can access their components by position. In Python, characters in a string are fetched by indexing - providing the numeric offset of the desired component in square brackets after … [Continue reading]

Python Strings: Part Four

In the previous articles, we introduced Python strings and covered escape sequences, raw strings and triple-quoted strings. Now we can cover some basic string operations. Strings can be concatenated using the + operator and repeated using the * … [Continue reading]

Python Strings: Part Three

As we saw in the previous article, escape sequences are handy for embedding special byte codes within strings. Sometimes, however, the special treatment of backslashes can cause problems. For example, let's assume we want to open a file called … [Continue reading]