📚

Python Data Structures Lecture Notes

Jul 29, 2024

Python Data Structures Lecture Notes

Introduction

  • Overview of important topics in Module 2
  • Focus on Lists, Strings, and Dictionaries as built-in data types in Python.

Lists in Python

  • Definition: Lists are a built-in data type used to store collections of items.
  • Characteristics:
    • Versatile data structures.
    • Elements can be of any data type (numbers, strings, etc.).

Basic Operations on Lists

  1. Adding Values:
    • Append: Add value at the end.
    • Insert:
      • Syntax: my_list.insert(index, value)
      • Example: my_list.insert(1, 'A')
  2. Removing Values:
    • Remove: Removes first occurrence of a value.
    • Pop: Removes value at specified index and returns it.
      • Example: my_list.pop(index)
  3. Finding Values:
    • Use in operator or index() method.
    • Example: if 'item' in my_list:
  4. Sorting Lists:
    • Use sort() function to create a sorted copy without modifying the original.

List vs Tuple

  • List: Mutable, can change contents. Suitable for collections of items needing modification.
  • Tuple: Immutable, contents cannot change, more efficient in terms of performance.
  • Conversion Example:
    • To create a tuple from a list: tuple(my_list)

Strings in Python

  • Definition: Strings are built-in data types used to represent text sequences.
  • Strings are surrounded by single or double quotation marks.

Common String Methods

  1. upper(): Converts all characters to uppercase.
    • Example: text.upper()
  2. replace(): Replaces occurrences of a word in the string.
    • Example: text.replace('old', 'new')

Traversing a List

  • Definition: Visiting each element of the list for operations (printing, modifying, searching).
  • Methods to Traverse:
    1. For Loop:
      • Example: for item in my_list:
    2. While Loop:
      • Example: while index < len(my_list):
    3. List Comprehension:
      • Example: [item**2 for item in my_list]
    4. Enumerate: Track both index and value.
      • Example: for index, value in enumerate(my_list):**

Dictionaries in Python

  • Definition: Unordered collection of key-value pairs, also known as associative arrays or hash maps.
  • Characteristics:
    • Accessed by keys, not index.
    • Example: my_dict = {'key': 'value'}

Key Methods in Dictionaries

  1. items(): Returns a view of all key-value pairs.
  2. keys(): Returns a view of all keys in the dictionary.
  3. values(): Returns a view of all values in the dictionary.

Differences between Dictionaries and Lists

  • List: Ordered collection, accessed by index.
  • Dictionary: Unordered collection, accessed by keys. Elements have no specific order.

Conclusion

  • Encouragement to keep learning about Python
  • Next sessions will cover additional topics. Happy learning!