Working with Lists and Dictionaries

This chapter explores Python lists and dictionaries, covering their properties, operations, and methods for manipulation, along with examples, ensuring a comprehensive understanding of these data structures.

Notes on Working with Lists and Dictionaries

1. Introduction to Lists

  • Definition: A list is an ordered collection of elements that is mutable, allowing for modification after creation. Lists can contain mixed data types: integers, floats, strings, and even other lists (nested lists).
  • Creation: Lists are defined using square brackets [], separating elements with commas. Examples:
    • list1 = [2, 4, 6, 8, 10]
    • list2 = ['a', 'e', 'i', 'o', 'u']
    • list3 = [100, 23.5, 'Hello']
    • list4 = [['Physics', 101], ['Chemistry', 202]]

2. Accessing and Modifying List Elements

  • Indexing: Elements are accessed by their index, starting from 0 for the first element, with negative indexing used to access items from the end of the list. For example:
    • list1[0] returns the first element.
    • list1[-1] returns the last element.
  • Mutability: Lists can be modified in place, e.g., changing an element at a specific index:
    • list1[3] = 'Black'

3. List Operations

  • Concatenation: Joining two lists using the + operator. It does not modify the original lists:
    • list1 + list2.
  • Repetition: Repeating list contents using the * operator:
    • list1 * 4.
  • Membership: Checking for value presence using in and not in:
    • 'a' in list2 returns True.
  • Slicing: Creating sublists by specifying start and end indices. It supports step sizes, providing flexibility in element selection:
    • list1[1:5], list1[::-1] (for reversal).

4. Traversing a List

  • Lists can be traversed using loops, commonly with for loops:
    for item in list1:
        print(item)
    

5. List Methods

  • Several built-in methods aid in manipulating lists. Here are a few common ones and their functionalities:
    • append(x): Adds an element x to the end of the list.
    • extend(iterable): Appends elements from iterable to the list.
    • insert(i, x): Inserts element x at index i.
    • remove(x): Removes the first occurrence of x from the list.
    • pop(i): Removes and returns the element at index i, defaulting to the last item if no index is specified.
    • sort(): Sorts the list in place.
    • reverse(): Reverses the list in place.
    • count(x): Returns the number of occurrences of x in the list.

6. Introduction to Dictionaries

  • Definition: A dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and can be of immutable types, while values can be of any type.
  • Creation: Defined using curly braces {}. Example:
    • dict1 = {'Mohan': 95, 'Ram': 89}.

7. Accessing Dictionary Items

  • Items are accessed via keys:
    • dict1['Ram'] returns 89.
  • Membership checking in dictionaries:
    • Include checks like if 'Mohan' in dict1: to see if the key exists.

8. Modifying Dictionaries

  • Dictionaries are mutable; items can be added, modified, or removed.
    • Adding: dict1['Shyam'] = 88
    • Modifying: dict1['Mohan'] = 100
    • Removing: del dict1['Ram']

9. Traversing a Dictionary

  • Use loops to access key-value pairs. Common methods:
    • Using items() to get key-value pairs:
    for key, value in dict1.items():
        print(key, ':', value)
    

10. Dictionary Methods

  • Important dictionary methods include:
    • len(): Returns the number of items.
    • keys(): Gets list of keys.
    • values(): Gets list of values.
    • items(): Gets list of key-value pairs.
    • get(key): Returns value for a given key or None.
    • update(dict): Merges another dictionary.

Summary of Key Points

  • Lists: Mutable sequences in square brackets, accessed by index.
  • Dictionaries: Unordered collections of key-value pairs, accessed via unique keys.
  • Mutability: Both data structures can be modified after creation.
  • Key Operations: Concatenation and slicing for lists; adding and updating for dictionaries.

Key terms/Concepts

  1. Lists are mutable and can contain mixed data types.
  2. Elements in a list are accessed via a zero-based index.
  3. Common list operations include concatenation and slicing.
  4. Lists include several built-in methods for manipulation such as append(), extend(), and sort().
  5. Dictionaries are unordered collections of key-value pairs with unique keys.
  6. Dictionary items are accessed using their keys instead of indexes.
  7. Both data structures are mutable, allowing for dynamic changes.
  8. Membership testing can be performed effectively in both lists and dictionaries.
  9. Slicing can create new sub-lists while maintaining the original list.
  10. Both structures support comprehensive traversal using loops.

Other Recommended Chapters