Built-in data Structures
Built-in Data Structures
List
A list in Python is a mutable, ordered collection used to store multiple items in a single variable. It is one of the most commonly used data structures in Python.
Key Characteristics of Lists
Ordered
- Items are stored in the order they are added.
- The order is preserved unless explicitly modified.
Mutable
- Lists can be changed after creation.
- You can:
Add (
append(),insert(),extend())Remove (
remove(),pop(),del)Modify items (
list[index] = new_value)
Heterogeneous
A list can store elements of different data types:
Indexed
Elements are accessed by position (index), starting at 0:
Dynamic Size
Lists can grow or shrink in size dynamically as elements are added or removed.
List Accessing:
1. Indexing
We can use the index operator [] to access an item in a list. List indices start at 0.
You can use positive or negative indices.
| Element | Index | Negative Index |
|---|---|---|
| 'apple' | 0 | -4 |
| 'banana' | 1 | -3 |
| 'cherry' | 2 | -2 |
| 'date' | 3 | -1 |
2. Slicing
It is used to access a range of elements. The values stored in a list can be accessed using the slice operator [] and [:] with indexes starting at 0 in the beginning of the list and working their way to end -1.
Tuple Operations
| Function | Description | Example Usage |
|---|---|---|
len(tuple) | Returns the number of items in the tuple. | len((1, 2, 3)) → 3 |
max(tuple) | Returns the largest item. Works with numbers or strings. | max((3, 5, 1)) → 5 |
min(tuple) | Returns the smallest item. | min((3, 5, 1)) → 1 |
tuple(sequence) | Converts a list, string, or other iterable into a tuple. | tuple([1, 2]) → (1, 2) |
sum(tuple) | Returns the total sum of elements (if all are numeric). | sum((1, 2, 3)) → 6 |
sorted(tuple) | Returns a sorted list from the tuple's items (does not modify tuple). | sorted((3, 1, 2)) → [1, 2, 3] |
any(tuple) | Returns True if at least one element is True. | any((0, False, 5)) → True |
all(tuple) | Returns True if all elements are True. | all((1, 2, 3)) → True |
Set
- In Python, a set is a collection of unordered and unindexed elements.
- Sets can store elements of different data types (integers, strings, floats, etc.).
- Sets are similar to lists and tuples, but they do not maintain order and do not allow duplicates.
- The elements of a set are immutable (cannot be changed), but the set itself is mutable (you can add or remove elements).
- Sets are defined using curly braces
{}and elements are separated by commas. - Python implements the set data type using the built-in
setclass. - Sets do not allow duplicate values. Any repeated item is automatically removed.
- Sets are unordered, so items appear in random order and cannot be accessed by index.
- Sets are useful when you need to store unique items and perform mathematical set operations (like union, intersection, difference).
Creating a Set in Python
A set is created using curly braces
{}or theset()constructor.Elements inside a set must be separated by commas.
Sets automatically remove duplicate values.
You can store elements of different data types in a single set.
set() ConstructorAccessing Set Elements
Set Operations
1. add()
Adds a single element.
2. update()
Adds multiple elements (from any iterable like list, tuple, or another set).
my_set.update([3, 4]) # {1, 2, 3, 4}
my_set.update((5, 6)) # {1, 2, 3, 4, 5, 6}
my_set.update({7, 8}) # {1, 2, 3, 4, 5, 6, 7, 8}
remove()Removes a specific element. Raises an error if the element doesn’t exist.
my_set.remove(2) # {1, 3}
my_set.remove(10) # KeyError
discard()Removes a specific element. Does nothing if the element doesn’t exist.
my_set.discard(3) # {1, 2}
my_set.discard(10) # No error
3. pop()
Removes and returns a random element (since sets are unordered).
removed = my_set.pop()
print(removed) # Could be 1, 2, or 3
4. clear()
Removes all elements from the set.
my_set.clear() # my_set becomes set()
| Operation | Symbol | Python Method | Meaning | Example Result |
|---|---|---|---|---|
| Union | ∪ | union() | All elements in A or B | {1, 2, 3, 4, 5, 6} |
| Intersection | ∩ | intersection() | Elements in both A and B | {3, 4} |
| Difference (A - B) | − | difference() | Elements in A but not in B | {1, 2} |
| Symmetric Difference | △ | symmetric_difference() | Elements in A or B but not both | {1, 2, 5, 6} |
Dictionary
- In Python, a dictionary is a collection of elements where each element is a pair of key and value.
- In Python, the dictionary data type (data structure) has implemented with a class known as dict.
- All the elements of a dictionary must be enclosed in curly braces, each element must be separated with a comma symbol, and every pair of key and value must be separated with colon ( : ) symbol.
- Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
- An item has a key and a corresponding value that is expressed as a pair (key: value).
Accessing Elements from Dictionary
- Using Key as index - The elements of a dictionary can be accessed using the key as an index.
- get( key ) - This method returns the value associated with the given key in the dictionary.
- Accessing the whole dictionary - In Python, we use the name of the dictionary to access the whole dictionary.
- items( ) - This is a built-in method used to access all the elements of a dictionary in the form of a list of key-value pair.
- keys( ) - This is a built-in method used to access all the keys in a dictionary in the form of a list.
- values( ) - This is a built-in method used to access all the values in a dictionary in the form of a list.
- <class 'dict'>
- 1
- Nani
- {'rollNo': 1, 'name': 'Nani', 'department': 'BSC', 'year': 2}
- dict_items([('rollNo', 1), ('name', 'Nani'), ('department', 'BSC'), ('year', 2)])
- dict_keys(['rollNo', 'name', 'department', 'year'])
- dict_values([1, 'Nani', 'BSC', 2])
Operations in Dictionary
Dictionaries in Python allow us to perform various operations such as adding, updating, deleting, and more.- Adding elements - To add a new key-value pair, simply assign a value to a new key.
- Updating elements - If the key already exists, assigning a new value will update it.
- pop( key ) - This method removes the element with a specified key from the dictionary.
- popitem( ) - This method removes the last element from the dictionary.
- clear( ) - This method removes all the elements from the dictionary. That means the clear( ) method make the dictionary empty. This method returns the None value.
- del keyword with dict[key] - This keyword deletes the element with the specified key from the dictionary. Once the del keyword has used on a dictionary, we can not access it in the rest of the code.
- del keyword - This keyword deletes the dictionary completely. Once the del keyword has used on a dictionary, we can not access it in the rest of the code.
Comments
Post a Comment