Gallery
Intro to Python
Share
Explore
Learn Python

icon picker
Lists, Sets, and Dictionaries

This section covers:
Lists
Sets
Dictionaries
In this section, you’ll learn more about three types of data structures. You can think of them as ways to organize and store data.

Lists

Lists are used to store sequences of values. They are useful if you want to keep track of the order of the values. The values in the list are called elements or items.
Here are some examples of lists. Notice how lists can store any number of items of any type. Lists can also be empty.

Accessing list elements

You can access elements in a list by using index notation. The first element is at index 0. For example, running print(cheeses[1]) will print Edam.

Adding elements

You can add elements to a list by calling the append function.

Removing elements

You can also remove elements from a list in a couple ways. If you know the index of the element, you can use pop.
If you know the element you want to remove, but you don’t know its index, you can use remove. This function does not return anything.

Length of a list

Here is how you get the length of a list:

Checking list membership

You can use the in keyword to check if an element is contained in a list. The expression will return True if the list contains the element and False otherwise.

Sets

Sets are like lists, but they do not store duplicate entries, and they are unordered (i.e. there is no “first” element in a set).
Here is how you can create a set in Python:

Adding elements

You can add elements to a set by calling the add function.
If you try to add an element that is already in the set, Python will ignore the add.

Removing elements

You can remove elements in a set by calling the remove function.

Checking set membership

You can use the in keyword to check if an element is contained in a set. The expression will return True if the set contains the element and False otherwise.

Dictionaries

Dictionaries are useful when you want to store values associated with a particular “key”. For example, if you want to keep track of your friend’s phone numbers, you can use a dictionary.
You can also add or update each key-value pair individually.
Capture d’écran 2020-10-04 à 11.54.33 AM.png

Accessing values

Here is how you retrieve the value associated with a given key in a dictionary.

Checking dictionary membership

You can use the in keyword to check if a something is a key in a dictionary.

Other dictionary functions

Here is how you get all the keys in a dictionary.
Here is how you get all the values in a dictionary.
Data Structure Tasks
9
Task
Status
1
Learn about lists
Not Started
2
Learn about sets
Not Started
3
Learn about dictionaries
Not Started
No results from filter

Next Section ➡️


Share
 
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.