📚

Understanding Python Lists, Tuples, and Dictionaries

Dec 27, 2024

Python Series: Lists, Tuples, and Dictionaries

Agenda

  • Lists in Python: Characteristics and exploration in Jupyter Notebook.
  • Tuples in Python: Characteristics and exploration in Jupyter Notebook.
  • Dictionaries in Python: Characteristics and exploration in Jupyter Notebook.

Lists in Python

  • Definition: Collection of objects, values, or items of different types, enclosed within square brackets and separated by commas.
  • Example: list1 = [1, "adam", 107, "usa"]
  • Indexing:
    • Forward Index: Starts from 0.
    • Reverse Index: Starts from -1.
  • Characteristics:
    • Ordered: Items have a defined order.
    • Accessible by index.
    • Stores various types: Numbers, strings, or other lists.
    • Mutable: Can change, add, or remove items.
    • Allows duplicate elements.

List Methods

  • append(): Adds an element at the end.
  • insert(): Adds an element at a specified position.
  • extend(): Adds elements of a list to the end of the current list.
  • index(): Returns the index of the first element with a specified value.
  • remove(): Removes an item with a specified value.
  • sort(): Sorts the list.
  • reverse(): Reverses the order of the list.
  • clear(): Removes all elements from the list.

Tuples in Python

  • Definition: Collection of objects, values, or items of different types, enclosed within parentheses and separated by commas.
  • Example: tup1 = (1, "adam", 107, "usa")
  • Characteristics:
    • Ordered: Items have a defined order.
    • Accessible by index.
    • Immutable: Cannot change, add, or remove items.
    • Allows duplicate elements.

Tuple Methods

  • index(): Access items using index (starts from zero).
  • slicing: Access a range of items using slicing operator.
  • concatenation: Add two tuples using the plus operator.
  • repetition: Repeat items using the multiplication operator.
  • count(): Returns the number of times a specified value occurs.

Dictionaries in Python

  • Definition: Collection of objects, values, or items stored in key-value pair format, enclosed within curly braces.
  • Example: dict1 = {"a": 1, "b": 2, "c": 3}
  • Characteristics:
    • Ordered: Items have a defined order (from Python 3.7).
    • Keys are unique, values can be duplicated.
    • Mutable: Can change, add, or remove items.

Dictionary Methods

  • clear(): Removes all elements from the dictionary.
  • get(): Returns the value of a specified key.
  • keys(): Returns a list of the dictionary's keys.
  • pop(): Removes the element with a specified key.
  • popitem(): Removes the last inserted key-value pair.
  • update(): Updates the dictionary with a key-value pair.
  • copy(): Copies the dictionary to a new dictionary.

Conclusion

  • Covered key characteristics and methods of lists, tuples, and dictionaries in Python.
  • Explored examples and practical applications using Jupyter Notebook.