List, Tuple, Dictionary
List, Tuple, Dictionary
Sure, let's cover the basics of lists in Python, including their definition, operators, and methods.
- A list in Python is a collection of items, ordered and mutable, separated by commas and enclosed
within square brackets `[]`.
List items are indexed, the first item has index [0], the second item has index [1] etc.
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.
If you add new items to a list, the new items will be placed at the end of the list.
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
- Lists can contain elements of different data types, including integers, floats, strings, or even other
lists.
1. **Concatenation (`+`):** Concatenates two lists to create a new list containing all the elements
from both lists.
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
```
2. **Repetition (`*`):** Repeats a list a specified number of times to create a new list.
```python
original_list = [1, 2, 3]
```
### List Methods:
```python
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
```
```python
my_list = [1, 2, 3]
```
3. **Remove (`remove()`):** Removes the first occurrence of a specified value from the list.
```python
my_list = [1, 2, 3, 2]
my_list.remove(2) # [1, 3, 2]
```
4. **Pop (`pop()`):** Removes and returns the element at a specified index. If no index is specified,
removes and returns the last element.
```python
my_list = [1, 2, 3]
```
5. **Index (`index()`):** Returns the index of the first occurrence of a specified value in the list.
```python
my_list = [1, 2, 3, 2]
index = my_list.index(2) # 1
```
6. **Count (`count()`):** Returns the number of occurrences of a specified value in the list.
```python
my_list = [1, 2, 3, 2]
count = my_list.count(2) # 2
```
7. **Sort (`sort()`):** Sorts the elements of the list in ascending order (or with a custom key
function).
```python
my_list = [3, 1, 2]
my_list.sort() # [1, 2, 3]
```
```python
my_list = [1, 2, 3]
my_list.reverse() # [3, 2, 1]
```
9. **Clear (`clear()`):** Removes all elements from the list, leaving it empty.
```python
my_list = [1, 2, 3]
my_list.clear() # []
```
```python
my_list = [1, 2, 3]
new_list = my_list.copy()
```
11. **Extend (`extend()`):** Appends the elements from another list to the end of the current list.
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2) # [1, 2, 3, 4, 5, 6]
```
12. **Slice (`[start:end:step]`):** Extracts a sublist from the list based on the specified start, end,
and step indices.
```python
my_list = [1, 2, 3, 4, 5]
```
These are some of the fundamental operators and methods you can use with lists in Python. Lists are
versatile data structures and support many more operations for manipulation and traversal.
DICTIONARIES
In Python, a dictionary is a built-in data type that represents a collection of key-value
pairs. It is an unordered, mutable, and indexed collection. Dictionaries are sometimes
also known as associative arrays or hashmaps in other programming languages.
Dictionary Definition:
A dictionary is defined using curly braces {}, with each key-value pair
separated by a colon : and each pair separated by commas.
Keys are unique and immutable, while values can be of any data type and
mutable. There cant be duplicate values.
Keys are used to access the corresponding values in the dictionary.
Example of a Dictionary:
In this dictionary:
"name", "age", and "city" are keys.
"John", 30, and "New York" are values.
Key-value pairs are separated by colons.
Certainly! Below is a comprehensive coverage of operators and methods commonly used with
dictionaries in Python:
```python
my_dict.clear() # {}
```
```python
```
3. **`fromkeys(iterable[, value])`:** Creates a new dictionary with keys from iterable and values set
to value (default is `None`).
```python
default_value = 0
```
4. **`get(key[, default])`:** Returns the value for the specified key. If the key is not found, it returns
the default value (default is `None`).
```python
```
```python
```
```python
```
```python
```
8. **`pop(key[, default])`:** Removes and returns the value for the specified key. If the key is not
found, it returns the default value (default is `None`).
```python
value = my_dict.pop("a") # 1
```
```python
```
10. **`setdefault(key[, default])`:** Returns the value for the specified key. If the key is not found, it
inserts the key with the specified default value (default is `None`).
```python
value = my_dict.setdefault("c", 3) # 3
```
11. **`update(iterable)`:** Updates the dictionary with the key-value pairs from another dictionary
or an iterable of key-value pairs.
```python
```
```python
my_dict.clear() # {}
```
```python
if "a" in my_dict:
```
if dict1 == dict2:
```
3. **Identity (`is`, `is not`):** Checks if two dictionaries refer to the same object.
```python
if dict1 is dict2:
```
These methods and operators provide a wide range of functionality for working with dictionaries in
Python, including creating, modifying, and accessing key-value pairs, as well as performing
comparisons.
TUPLES
In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists,
tuples are immutable, meaning once they are created, their elements cannot be changed,
added, or removed.
Tuples are defined by enclosing the elements in parentheses `()`, optionally separated by
commas. For example:
```python
my_tuple = (1, 2, 3, 4, 5)
```
Tuples can contain elements of different data types, including integers, floats, strings, and
even other tuples. Here's an example of a tuple with mixed data types:
```python
mixed_tuple = ('apple', 3.14, True, (1, 2, 3))
```
You can access elements of a tuple using indexing, just like with lists. Indexing in Python is
zero-based, meaning the first element is at index 0, the second element is at index 1, and so
on. For example:
```python
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Output: 10
print(my_tuple[2]) # Output: 30
```
Tuples support slicing, which allows you to create a new tuple by extracting a subset of
elements from an existing tuple. For example:
```python
my_tuple = (1, 2, 3, 4, 5)
subset_tuple = my_tuple[1:4] # Extract elements from index 1 to index 3
print(subset_tuple) # Output: (2, 3, 4)
```
Tuples are commonly used for representing fixed collections of items, such as coordinates,
database records, or function return values. They are also often used in situations where
immutability and hashability are desired, such as keys in dictionaries.
One important point to note is that if a tuple contains mutable objects like lists, you can
modify the mutable objects themselves, but you cannot reassign a new value to the tuple's
elements. This is because the tuple itself is immutable, but the mutable objects it contains
are not.
Tuples in Python are immutable, meaning they cannot be modified after creation.
Consequently, tuple objects have fewer methods compared to lists. However, they support
some operations and methods that are useful for working with tuples. Here are some
common tuple operations and methods:
2. **Index**: Returns the index of the first occurrence of a specified value in the tuple.
```python
tuple1 = ('a', 'b', 'c', 'd', 'b')
print(tuple1.index('b')) # Output: 1
```
These are the basic operations and methods available for tuples in Python. Since tuples are
immutable, they don't have methods like `append()`, `remove()`, or `pop()` that modify the
tuple in place, unlike lists.