4 Dealing with sequence data

 

This chapter covers

  • Using slice objects to retrieve and manipulate subsequences
  • Combining the use of positive and negative indexing in item retrieval
  • Finding items in a sequence
  • Unpacking a sequence
  • Considering data models other than lists

In chapter 3, you learned to use lists and tuples to hold data. One shared characteristic of lists and tuples is that the held items have a specific order. These two data structures are examples of the more general data type sequence. Python has other sequence data types, such as strings and bytes. These sequence data models are essential data structures that we use in our projects. The reason is simple: we use data to model real life, which is full of ordered objects/events, such as waiting lines, written languages, and house numbers, to name a few. Thus, the effective handling of sequence data is a universal need in programming projects regardless of our business specialty.

From Python’s implementation perspective, these sequence data structures share many characteristics, and it’s worth discussing them together here. You want to kill two birds with one stone, and you’ll find that the skills you may have thought applied only to a specific data model (such as unpacking a tuple object) can be applied to all sequence data models. As a related note, even though I’ll mostly use lists or strings in the examples in this chapter, don’t mistakenly think that these techniques are available only to lists or strings.

4.1 How do I retrieve and manipulate subsequences with slice objects?

4.1.1 Taking advantage of the full features of slicing

4.1.2 Not confusing slices with ranges

4.1.3 Using named slice objects to process sequence data

4.1.4 Manipulating list items with slicing operations

4.1.5 Discussion

4.1.6 Challenge

4.2 How do I use positive and negative indexing to retrieve items?

4.2.1 Positive indexing starts from the beginning of the list

4.2.2 Negative indexing starts from the end of the list

4.2.3 Combining positive and negative indices as needed

4.2.4 Discussion

4.2.5 Challenge