Building lists – literals, appending, and comprehensions
If we've decided to create a collection based on each item's position in the container—a list
—we have several ways of building this structure. We'll look at a number of ways we can assemble a list object from the individual items.
In some cases, we'll need a list because it allows duplicate values. This is common in statistical work, where we will have duplicates but we don't require the index positions. A different structure, called a multiset, would be useful for a statistically oriented collection that permits duplicates. This kind of collection isn't built-in (although collections.Counter
is an excellent multiset, as long as items are immutable), leading us to use a list
object.
Getting ready
Let's say we need to do some statistical analyses of some file sizes. Here's a short script that will provide us with the sizes of some files...