Informatics Practices: Class 11 — Chapter 4: Working with Lists and Dictionaries

Introduction to Lists

The data type list is an ordered sequence in Python that is mutable and composed of one or more elements. Unlike strings, which contain only characters, a list can group elements of mixed data types, including integers, floats, strings, tuples, or even other nested lists. Elements of a list are enclosed in square brackets [] and separated by commas.

  
    >>> list1 = [2, 4, 6, 8, 10, 12]
    >>> print(list1)
    [2, 4, 6, 8, 10, 12]
  
Accessing Elements in a List

Each element in a list is accessed using an integer value called an index . Python supports two-way indexing:

  • Forward Indexing: Starts from 0 for the first element, increasing sequentially to n-1 (where n is the length of the list).
  • Backward/Negative Indexing: Starts from -1 for the last element, decreasing sequentially to -n for the first element.

Attempting to access an index outside the valid range raises an IndexError .

  
    >>> list1 = [2, 4, 6, 8, 10, 12]
    >>> list1[0]
    2
    >>> list1[-1]
    12
    >>> list1[1+4]
    12
    >>> list1[15]
    IndexError: list index out of range
  
Lists are Mutable

In Python, lists are mutable , meaning their elements can be modified, updated, or overwritten in-place after creation without changing the list's memory identity.

  
    >>> list1 = ['Red', 'Green', 'Blue', 'Orange']
    >>> list1[3] = 'Black'
    >>> list1
    ['Red', 'Green', 'Blue', 'Black']
  
List Operations

Python supports several operators to manipulate and evaluate list contents dynamically.

Concatenation (+)

The concatenation operator + joins two or more lists together to produce a new list. Both operands must be of type list ; mixing types raises a TypeError .

  
    >>> list1 = [1, 3, 5]
    >>> list2 = [2, 4, 6]
    >>> list1 + list2
    [1, 3, 5, 2, 4, 6]
  
Repetition (*)

The repetition operator * replicates the contents of a list a specified number of \times, returning a new concatenated list.

  
    >>> list1 = ['Hello']
    >>> list1 * 4
    ['Hello', 'Hello', 'Hello', 'Hello']
  
Membership (in, not in)

The membership operators evaluate whether an element exists within a list, returning a boolean value ( True or False ).

  
    >>> list1 = ['Red', 'Green', 'Blue']
    >>> 'Green' in list1
    True
    >>> 'Cyan' not in list1
    True
  
Slicing

Slicing operations allow the extraction of a sublist from an existing list using the syntax list[start:stop:step] .

  • start: The starting index of the slice (inclusive). Defaults to 0.
  • stop: The ending index of the slice (exclusive). Defaults to the end of the list.
  • step: The increment value between elements. Can be negative to slice in reverse.
  
    >>> list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
    >>> list1[2:6]
    ['Blue', 'Cyan', 'Magenta', 'Yellow']
    >>> list1[::-1]
    ['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue', 'Green', 'Red']
  
Traversing a List

Traversing refers to accessing each element of a list systematically. This can be achieved using loops.

Direct Element Iteration

Iterating directly over the elements of a list using a for loop:

  
    >>> list1 = ['Red', 'Green', 'Blue']
    >>> for item in list1:
    ...     print(item)
  
Index-Based Iteration

Iterating using index positions generated by combining range() and len() :

  
    >>> for i in range(len(list1)):
    ...     print(list1[i])
  
List Methods and Built-in Functions

Python provides a rich set of built-in functions and methods to manipulate lists. The table below details these operations:

Computing Method / Keyword Exact Syntactic Execution Signature Supported Parameters & Arguments Algorithmic Purpose & Output Representation
len() len(list) A list object. Returns an integer representing the total number of elements in the list.
list() list([sequence]) An optional sequence/iterable object. Creates an empty list if no argument is passed, or converts an iterable sequence into a list.
append() list.append(element) A single element (can be any data type, including another list). Appends the single element to the end of the list. Modifies the list in-place.
extend() list.extend(sequence) An iterable sequence (list, tuple, etc.). Appends each individual element of the passed sequence to the end of the list. Modifies the list in-place.
insert() list.insert(index, element) An integer index, and the element to insert. Inserts the element at the specified index position, shifting subsequent elements to the right.
count() list.count(element) The element to search for. Returns an integer count of how many \times the specified element appears in the list.
index() list.index(element) The element to search for. Returns the index of the first occurrence of the element. Raises a ValueError if the element is not present.
Note: Labeled as find() in some legacy textbook tables, but executed as index().
remove() list.remove(element) The element to be removed. Removes the first occurrence of the specified element from the list. Raises a ValueError if the element is not found.
pop() list.pop([index]) An optional integer index (defaults to -1). Removes and returns the element at the specified index. If no index is provided, removes and returns the last element.
reverse() list.reverse() None. Reverses the order of elements in the list in-place.
sort() list.sort(reverse=False) Optional boolean parameter reverse . Sorts the elements of the list in-place in ascending order by default (or descending if reverse=True ).
sorted() sorted(iterable, reverse=False) An iterable sequence, and an optional reverse boolean. Returns a new sorted list containing the elements of the passed iterable, leaving the original sequence unmodified.
min() , max() , sum() min(list) , max(list) , sum(list) A list containing comparable elements (numeric for sum). Returns the minimum value, maximum value, or arithmetic sum of all elements in the list, respectively.
Introduction to Dictionaries

The data type dictionary falls under the category of mappings. It is an unordered, mutable collection of key-value pairs enclosed in curly braces {} . Each key is separated from its value by a colon ( : ), and consecutive items are separated by commas.

Creating and Accessing Dictionaries

Dictionaries are accessed via their keys rather than index positions.

  
    >>> dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}
    >>> dict1['Ram']
    89
    >>> dict1['Shyam']
    KeyError: 'Shyam'
  
Membership Operations

Membership operators ( in , not in ) check for the presence of a key in the dictionary, not a value.

  
    >>> 'Suhel' in dict1
    True
    >>> 95 in dict1
    False
  
Mutability: Adding and Modifying Items

Dictionaries are mutable. New key-value pairs can be added, and existing values can be updated by direct assignment.

  
    >>> dict1['Meena'] = 78  # Adding a new item
    >>> dict1['Suhel'] = 93.5 # Modifying an existing item
    >>> dict1
    {'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85, 'Meena': 78}
  
Traversing a Dictionary

A dictionary can be traversed using a for loop in two primary ways:

Method 1: Iterating Over Keys
  
    >>> for key in dict1:
    ...     print(key, ':', dict1[key])
  
Method 2: Iterating Over Key-Value Pairs
  
    >>> for key, value in dict1.items():
    ...     print(key, ':', value)
  
Dictionary Methods and Built-in Functions

The table below details the built-in functions and methods used to manipulate dictionaries:

Computing Method / Keyword Exact Syntactic Execution Signature Supported Parameters & Arguments Algorithmic Purpose & Output Representation
len() len(dictionary) A dictionary object. Returns an integer representing the total number of key-value pairs in the dictionary.
dict() dict(sequence) A sequence of key-value pairs (e.g., list of tuples). Creates a dictionary from the provided sequence of key-value pairs.
keys() dictionary.keys() None. Returns a view object containing all the keys of the dictionary.
values() dictionary.values() None. Returns a view object containing all the values of the dictionary.
items() dictionary.items() None. Returns a view object containing tuples of key-value pairs.
get() dictionary.get(key[, default]) A key to search for, and an optional default return value. Returns the value associated with the key. If the key does not exist, returns None (or the specified default value) instead of raising a KeyError.
update() dictionary.update(other_dict) Another dictionary object. Appends key-value pairs from the argument dictionary to the caller dictionary, overwriting values for any matching keys.
clear() dictionary.clear() None. Removes all items from the dictionary, leaving it empty.
del del dictionary[key] or del dictionary A specific key to delete, or the dictionary object itself. Deletes the key-value pair associated with the specified key, or deletes the entire dictionary object from memory.