What are the main data structures in Python, and how do I use them?

Python provides several built-in data structures that are commonly used:

  • Lists: Lists are ordered, mutable collections that can store elements of different types. They are defined using square brackets []. You can perform operations like accessing elements by index, adding or removing items, and iterating over the list using loops.
  • Dictionaries: Dictionaries are unordered collections of key-value pairs. They are defined using curly braces {}. You can access values by their corresponding keys, add or remove key-value pairs, and iterate over the keys, values, or key-value pairs.
  • Tuples: Tuples are immutable sequences that can store elements of different types. They are defined using parentheses (). Tuples are similar to lists but cannot be modified once created.
  • Sets: Sets are unordered collections of unique elements. They are defined using curly braces {} or the set() function. Sets support operations like adding or removing elements, performing set operations like union, intersection, and difference, and checking for membership.

Each data structure has its own set of methods and operations, allowing you to manipulate and work with data efficiently in various scenarios.