Chapter 3. Built-in Data Structures, Functions, and Files
This chapter discusses capabilities built into the Python language that will be used ubiquitously throughout the book. While add-on libraries like pandas and NumPy add advanced computational functionality for larger datasets, they are designed to be used together with Python’s built-in data manipulation tools.
We’ll start with Python’s workhorse data structures: tuples, lists, dicts, and sets. Then, we’ll discuss creating your own reusable Python functions. Finally, we’ll look at the mechanics of Python file objects and interacting with your local hard drive.
3.1 Data Structures and Sequences
Python’s data structures are simple but powerful. Mastering their use is a critical part of becoming a proficient Python programmer.
Tuple
A tuple is a fixed-length, immutable sequence of Python objects. The easiest way to create one is with a comma-separated sequence of values:
In[2]:tup=4,5,6In[3]:tupOut[3]:(4,5,6)
When you’re defining tuples in more complicated expressions, it’s often necessary to enclose the values in parentheses, as in this example of creating a tuple of tuples:
In[4]:nested_tup=(4,5,6),(7,8)In[5]:nested_tupOut[5]:((4,5,6),(7,8))
You can convert any sequence or iterator to a tuple by invoking
tuple:
In[6]:tuple([4,0,2])Out[6]:(4,0,2)In[7]:tup=tuple('string')In[8]:tupOut[8]:('s','t','r','i','n','g')
Elements can be accessed with square brackets [] as with most other sequence ...
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