3 Using built-in data containers

 

This chapter covers

  • Choosing lists over tuples and vice versa
  • Sorting lists that consist of complex data types
  • Using named tuples as a data container model
  • Accessing a dictionary’s data
  • Understanding hashability and its implications for dictionaries and sets
  • Applying set operations to manipulate nonset data

As a general-purpose programming language, Python provides a range of built-in data types for different purposes, including collection types. These collection types of data serve as containers to hold integers, strings, instances of custom classes, and all other kinds of objects. In every project, we deal with multiple objects at the same time, and these scenarios often require data containers to handle these objects. Every modern language has data containers as its core data models, highlighting the importance of data containers as building blocks for any programming project. As you’ll see in chapter 14 when we build our task management app, we’ll use data containers for a variety of jobs, such as using a list to hold custom instances of the Task class (chapter 8). In this chapter, we’ll discuss the most common built-in data containers, including lists, tuples, dictionaries, and sets. Please note that this chapter isn’t intended to provide an exhaustive review of all the functionalities related to these data models. Instead, we’ll focus on essential topics that matter most in our projects.

3.1 How do I choose between lists and tuples?

3.1.1 Using tuples for immutability and using lists for mutability

3.1.2 Using tuples for heterogeneity and using lists for homogeneity

3.1.3 Discussion

3.1.4 Challenge

3.2 How do I sort lists of complicated data using custom functions?

3.2.1 Sorting lists using the default order

3.2.2 Using a built-in function as the sorting key

3.2.3 Using custom functions for more complicated sorting needs

3.2.4 Discussion

3.2.5 Challenge

3.3 How do I build a lightweight data model using named tuples?

3.3.1 Understanding alternative data models

3.3.2 Creating named tuples to hold data

sitemap