CH - 8 Data Structures
Introduction to lists, tuples, dictionaries, and sets.
Python provides several built-in data structures to store and organize data efficiently.
- Lists: A list is a collection of items that can hold multiple values at once. Lists are useful for storing related data, like the names of students in a class. Lists are also flexible because you can add or remove items, and even change the values in a list.
- Tuples: A tuple is similar to a list, but once a tuple is created, you cannot change it. This makes tuples useful for data that should not be altered. For example, the dimensions of a rectangle (width, height) might be stored in a tuple since these values are usually fixed.
- Sets: A set is an unordered collection of unique items. Unlike lists or tuples, sets do not allow duplicate values. They are useful for storing data where you only care about unique entries. For example, a set could store all unique words from a text.
- Dictionaries: A dictionary stores data in key-value pairs. Each key is unique, and it maps to a corresponding value. Dictionaries are extremely useful for looking up information quickly. For instance, you can use a dictionary to store a person’s name as a key and their phone number as the value. They also have inbuilt functions like
Some dictionary methods are as follows:
- update(): Merges the contents of another dictionary or iterable of key-value pairs into the dictionary.
- setdefault(): Returns the value of a specified key; if the key does not exist, it inserts the key with a specified default value.
- clear(): Removes all items from the dictionary, resulting in an empty dictionary.
- get(): Retrieves the value for a specified key; if the key is not found, it returns None or a default value if provided.
- pop(): Removes and returns the value associated with a specified key; raises a KeyError if the key is not found unless a default value is provided.
- keys(): Returns a view object of all the keys in the dictionary.
- values(): Returns a view object of all the values in the dictionary.
- items(): Returns a view object of all key-value pairs in the dictionary as tuples.
These data structures allow you to organize and store data in an efficient way, and they provide various methods to access and manipulate the data.