This lesson is in the early stages of development (Alpha version)

Lists and dictionaries in Python

Overview

Teaching: 15 min
Exercises: 5 min
Questions
  • What other data structures are there?

Objectives
  • Understand the use of lists and dictionaries in Python.

Lists

Example of list creation:

my_list = [1, 2, 3, 'apple', 'banana', 'cherry']

Indexing and accessing elements:

last_element = my_list[-1]   # Accessing the last element

Manipulating lists:

Examples of manipulation:

my_list.append('orange')     # Adds 'orange' to the end of the list
my_list.insert(2, 'pear')    # Inserts 'pear' at index 2
my_list.remove('banana')     # Removes the first occurrence of 'banana'
my_list.pop()                # Removes and returns the last element
my_list[0] = 'grape'         # Updates the first element to 'grape'

Dictionaries

Example of dictionary creation:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

Accessing elements:

Example of accessing elements:

person_name = my_dict['name']   # Accessing value corresponding to 'name' key

Manipulating dictionaries:

Examples of manipulation:

my_dict['gender'] = 'Male'     # Adds 'gender': 'Male' to the dictionary
del my_dict['age']             # Removes the key 'age' and its value
my_dict['city'] = 'Los Angeles' # Updates the value of 'city' key to 'Los Angeles'

Key Points

  • Dictionaries: Efficient for fast key-based retrieval and storing data with unique identifiers.

  • Lists: Versatile collections for storing ordered heterogeneous data types with various operations like indexing and appending.