Chapter 9. Common Tasks in Python
At this point, we have covered the syntax of Python, its basic data types, and many of our favorite functions in the Python library. This chapter assumes that all the basic components of the language are at least understood and presents some ways in which Python is, in addition to being elegant and “cool,” just plain useful. We present a variety of tasks common to Python programmers. These tasks are grouped by categories—data structure manipulations, file manipulations, etc.
Data Structure Manipulations
One of Python’s greatest features is that it provides the list, tuple, and dictionary built-in types. They are so flexible and easy to use that once you’ve grown used to them, you’ll find yourself reaching for them automatically.
Making Copies Inline
Due to Python’s reference management scheme, the
statement a = b doesn’t make a copy of the
object referenced by b ; instead, it makes a new
reference to that object. Sometimes a new copy of an object, not just
a shared reference, is needed. How to do this depends on the type of
the object in question. The simplest way to make copies of
lists
and
tuples
is somewhat odd. If myList is a list, then to make
a copy of it, you can do:
newList = myList[:]
which you can read as “slice from beginning to end,” since you’ll remember from Chapter 2, that the default index for the start of a slice is the beginning of the sequence (0), and the default index for the end of a slice is the end of sequence. Since tuples support ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access