Python Friday #4: Lists, Dictionaries, Sets & Tuples

This week I learned more about the different data structures in Python. In the second try I got a better understanding on the subtle differences in creating collections. Collections are an important way to group data and move it around and I hope this post will help me to keep them apart.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Lists

Lists are a mutable collection of elements. You define a list using [] and separate the elements by a comma:

You can select the different elements using a 0-based index:

The same is possible using an index starting at the end of the list:

I hope this image explains how those indexes change by the direction you want to access the elements:
Index positions in Python

Your lists can contain various datatypes side-by-side:

Since lists are mutable, you can change a list by adding new elements or removing them:

We can reverse the elements in a list:

 

Tuples

Tuples look like lists, but they are immutable and cannot be changed after you created them. You create a tuple using () and separate the elements by a comma:

You can skip the () and just use the commas:

The example above is called tuple packing, in which the numbers 4, 5 and 6 are packed together. You can reverse this (called sequence unpacking) and assign each element to a different variable:

 

Dictionaries

Dictionaries are a collection of key/value pairs that have no particular order. You can create a dictionary by using {} and separate the key from its value with a colon:

You get the value for a key by using the index operation:

You can replace an existing value by assigning a new value to that key. If this key does not exist, a new entry is added:

 

Sets

To show why I had problems with keeping the different structures apart I like to talk about sets as the last structure of this post. Sets are unordered, mutable collections with no duplicate elements. You create sets like a list, but use {} instead of []:

You can specify duplicated elements when you create your set, but the set will not add them:

You can add more elements using add(), but it will ignore your addition when the element is already present:

As with lists, we can change our set by adding new elements or removing them:

Warning: You cannot create an empty set using {}, then that creates a dictionary:

To create an empty set, you need to call the function set() without any arguments:

 

Next

There are many more built-in data types and structures that I need to understand. I will cover them as I learn more about Python. The next step for me is to learn more about strings.

3 thoughts on “Python Friday #4: Lists, Dictionaries, Sets & Tuples”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.