Learn Programming with Python — Introduction to Compound Data Types: Lists

Richard Quinn
Level Up Coding

--

We’re finally getting to the heart of what makes Python magical! Lists are an enormously powerful tool for creating beautiful software.

What is the List Compound Data Type?

Lists are exactly what we might be expecting: the list compound data type contains an ordered list of objects. The list — unlike the set — may contain duplicates and is in a specific order. Unlike the tuple, the elements of the list itself don’t in total comprise a record.

Let’s say you spend some time recording the species of each bird you see from your window:

recorded_birds = ["crow", "sparrow", "sparrow", "robin", "crow", "sparrow"]

The contents of this list contains duplicates. In this way it is possible to know two separate things: 1) how many individual birds (six) and 2) how many different species (three) were observed. The set data type is only able to represent the number of species. In Python, we create a list using square brackets [] or by using the list() constructor. In Python, the list is similar to what other programming languages might call an array.

Let’s cast (convert) this list to a set:

In my code editor I get this output:

What’s going on here?

  • On line 1, I create the list of recorded_birds, each observed bird is an entry in the list.
  • On line 2 I cast the list to a set called recorded_species
  • On lines 3 and 4, I print the list and the set to the console
  • From the output, you can identify the list because it is enclosed in square brackets []. The original order is preserved.
  • From the output, you can identify the set because it is enclosed in curly brackets…

--

--

I am a software engineering manager with over 25 years of experience. I am working to improve people’s health. Based in Basel, Switzerland.