Chapter 5. Lists, tuples, and sets

 

This chapter covers

  • Manipulating lists and list indices
  • Modifying lists
  • Sorting
  • Using common list operations
  • Handling nested lists and deep copies
  • Using tuples
  • Creating and using sets

In this chapter, I discuss the two major Python sequence types: lists and tuples. At first, lists may remind you of arrays in many other languages, but don’t be fooled: lists are a good deal more flexible and powerful than plain arrays.

Tuples are like lists that can’t be modified; you can think of them as a restricted type of list or as a basic record type. I discuss the need for such a restricted data type later in the chapter. This chapter also discusses a newer Python collection type: sets. Sets are useful when an object’s membership in the collection, as opposed to its position, is important

Most of the chapter is devoted to lists, because if you understand lists, you pretty much understand tuples. The last part of the chapter discusses the differences between lists and tuples in both functional and design terms.

5.1. Lists are like arrays

A list in Python is much the same thing as an array in Java or C or any other language; it’s an ordered collection of objects. You create a list by enclosing a comma-separated list of elements in square brackets, like so:

# This assigns a three-element list to x
x = [1, 2, 3]

5.2. List indices

5.3. Modifying lists

5.4. Sorting lists

5.5. Other common list operations

5.6. Nested lists and deep copies

5.7. Tuples

5.8. Sets

Summary

sitemap