Skip to content

Commit 962dcc4

Browse files
authored
Update 6. Basic Data Structures.md
1 parent bf5ccf7 commit 962dcc4

File tree

1 file changed

+186
-20
lines changed

1 file changed

+186
-20
lines changed

Python/6. Basic Data Structures.md

+186-20
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
## 6. Python Basic Data Structures and Access Methods:
2-
32
## 1. Lists:
43
- Definition: Lists are ordered collections of items, which can be of any data type. They are mutable, meaning their elements can be changed after creation.
54
- Access Methods:
@@ -28,6 +27,35 @@
2827
my_list.remove(3) # Removes the first occurrence of 3
2928
my_list.sort() # Sorts the list in ascending order
3029
```
30+
- List Comprehensions: List comprehensions provide a concise way to create lists. They consist of an expression followed by a for clause, then zero or more for or if clauses.
31+
```python
32+
squares = [x**2 for x in range(10)]
33+
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
34+
```
35+
- Nested Lists: Lists can contain other lists as elements, enabling the creation of nested data structures.
36+
```python
37+
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
38+
print(nested_list[1][0]) # Output: 4
39+
```
40+
- List Operations: Python supports various operations on lists such as concatenation (`+`), repetition (`*`), membership (`in`), and length (`len()`).
41+
```python
42+
list1 = [1, 2, 3]
43+
list2 = [4, 5, 6]
44+
concatenated_list = list1 + list2
45+
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
46+
```
47+
- List Unpacking: Unpack the elements of a list into individual variables.
48+
```python
49+
my_list = [1, 2, 3]
50+
a, b, c = my_list
51+
print(a, b, c) # Output: 1 2 3
52+
```
53+
- List Aliasing vs. Cloning: Understanding the difference between aliasing (multiple names referencing the same list) and cloning (creating a separate copy of a list).
54+
```python
55+
original_list = [1, 2, 3]
56+
aliased_list = original_list
57+
cloned_list = original_list[:]
58+
```
3159

3260
## 2. Tuples:
3361
- Definition: Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation.
@@ -42,6 +70,23 @@
4270
my_tuple = (1, 2, 3, 4, 5)
4371
print(my_tuple[1:4]) # Output: (2, 3, 4)
4472
```
73+
- Tuple Packing and Unpacking: Tuples can be created without parentheses by simply separating the values with commas. Tuple unpacking allows assigning multiple variables at once.
74+
```python
75+
my_tuple = 1, 2, 3 # Tuple packing
76+
a, b, c = my_tuple # Tuple unpacking
77+
print(a, b, c) # Output: 1 2 3
78+
```
79+
- Tuple Methods: While tuples are immutable, they have a few methods like `count()` and `index()` for basic operations.
80+
```python
81+
my_tuple = (1, 2, 2, 3, 4, 5)
82+
print(my_tuple.count(2)) # Output: 2 (count occurrences of 2)
83+
print(my_tuple.index(4)) # Output: 4 (get index of the first occurrence of 4)
84+
```
85+
- Advantages of Tuples: Tuples offer advantages such as immutability (data integrity), faster iteration, and being used as dictionary keys.
86+
- Use Cases: Tuples are often used for representing fixed collections of items, such as coordinates, database records, and function return values.
87+
- Immutable vs. Mutable: Understanding the difference between immutable objects like tuples and mutable objects like lists is crucial for designing efficient and reliable programs.
88+
89+
4590

4691
## 3. Dictionaries:
4792
- Definition: Dictionaries are unordered collections of key-value pairs. They are mutable and indexed by unique keys.
@@ -56,6 +101,42 @@
56101
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
57102
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
58103
```
104+
- Adding and Modifying Items: Dictionaries allow adding new key-value pairs or modifying existing ones using assignment.
105+
```python
106+
my_dict = {'name': 'John', 'age': 30}
107+
my_dict['city'] = 'New York' # Add a new key-value pair
108+
my_dict['age'] = 31 # Modify the value of an existing key
109+
```
110+
- Removing Items: Use the `pop()` method to remove a specific key-value pair or the `clear()` method to remove all items.
111+
```python
112+
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
113+
my_dict.pop('age') # Remove the key-value pair with the key 'age'
114+
my_dict.clear() # Remove all items from the dictionary
115+
```
116+
- Dictionary Comprehensions: Similar to list comprehensions, dictionary comprehensions allow creating dictionaries in a concise manner.
117+
```python
118+
squares = {x: x**2 for x in range(5)}
119+
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
120+
```
121+
- Nested Dictionaries: Dictionaries can contain other dictionaries as values, enabling the creation of nested data structures.
122+
```python
123+
student = {
124+
'name': 'John',
125+
'age': 30,
126+
'address': {
127+
'city': 'New York',
128+
'zip': '10001'
129+
}
130+
}
131+
print(student['address']['city']) # Output: New York
132+
```
133+
- Dictionary Aliasing vs. Cloning: Similar to lists, dictionaries can be aliased or cloned, leading to different behaviors.
134+
```python
135+
original_dict = {'name': 'John', 'age': 30}
136+
aliased_dict = original_dict
137+
cloned_dict = original_dict.copy()
138+
```
139+
59140

60141
## 4. Sets:
61142
- Definition: Sets are unordered collections of unique elements. They are mutable but do not support duplicate elements.
@@ -71,26 +152,33 @@
71152
my_set.add(4) # Adds 4 to the set
72153
my_set.remove(2) # Removes 2 from the set
73154
```
74-
## 5. Strings:
75-
- Definition: Strings are immutable sequences of characters. They can be accessed and manipulated using various methods.
76-
- Access Methods:
77-
- Indexing: Access individual characters using their indices.
78-
```python
79-
my_string = "Hello"
80-
print(my_string[0]) # Output: H
81-
```
82-
- Slicing: Extract substrings using slicing notation.
83-
```python
84-
my_string = "Hello"
85-
print(my_string[1:3]) # Output: el
86-
```
87-
- String Methods: Python provides numerous methods to manipulate strings such as `upper()`, `lower()`, `split()`, `join()`, `strip()`, `replace()`, etc.
88-
```python
89-
my_string = "Hello, world"
90-
print(my_string.upper()) # Output: HELLO, WORLD
91-
```
155+
- Set Operations: Sets support various operations such as union, intersection, difference, and symmetric difference.
156+
```python
157+
set1 = {1, 2, 3}
158+
set2 = {3, 4, 5}
159+
union_set = set1.union(set2) # Union of set1 and set2
160+
intersection_set = set1.intersection(set2) # Intersection of set1 and set2
161+
difference_set = set1.difference(set2) # Elements in set1 but not in set2
162+
symmetric_difference_set = set1.symmetric_difference(set2) # Elements in either set1 or set2 but not both
163+
```
164+
- Set Comprehensions: Similar to list and dictionary comprehensions, set comprehensions allow creating sets in a concise manner.
165+
```python
166+
squares = {x**2 for x in range(5)}
167+
print(squares) # Output: {0, 1, 4, 9, 16}
168+
```
169+
- Frozen Sets: Frozen sets are immutable counterparts of sets and can be used as dictionary keys or elements of another set.
170+
```python
171+
my_set = frozenset([1, 2, 3])
172+
```
173+
- Use Cases: Sets are useful for tasks that involve checking for uniqueness or performing mathematical set operations.
174+
- Set Aliasing vs. Cloning: Like other mutable objects, sets can be aliased or cloned, resulting in different behaviors.
175+
```python
176+
original_set = {1, 2, 3}
177+
aliased_set = original_set
178+
cloned_set = original_set.copy()
179+
```
92180

93-
## 6. Arrays:
181+
## 5. Arrays:
94182
- Definition: Arrays in Python are data structures used to store collections of elements. Unlike lists, arrays can only store elements of the same data type. Arrays are created using the `array` module.
95183
- Access Methods:
96184
1. Indexing: Access individual elements using their indices.
@@ -124,6 +212,84 @@
124212
arr.append(6)
125213
print(arr) # Output: array('i', [1, 2, 3, 4, 5, 6])
126214
```
215+
- Multi-dimensional Arrays: Arrays can be multi-dimensional, allowing the storage of data in multiple dimensions, such as matrices.
216+
```python
217+
from array import array
218+
219+
arr = array('i', [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
220+
print(arr[1][2]) # Output: 6
221+
```
222+
223+
- Array Methods: In addition to basic methods like `append()` and `extend()`, arrays support methods such as `fromlist()` and `tolist()` for conversion between arrays and lists.
224+
```python
225+
from array import array
226+
227+
arr = array('i', [1, 2, 3])
228+
list_representation = arr.tolist() # Convert array to list
229+
print(list_representation) # Output: [1, 2, 3]
230+
```
231+
232+
- Advantages of Arrays: Arrays are advantageous for numerical computations and memory efficiency due to their fixed type and contiguous memory allocation.
233+
234+
- Limitations: Arrays in Python are less flexible than lists because they can only store elements of the same data type and have a fixed size upon creation.
235+
236+
- Use Cases: Arrays are commonly used in numerical computations, scientific computing, and implementing algorithms that require fixed-size data structures.
237+
238+
239+
## 6. Strings:
240+
- Definition: Strings are immutable sequences of characters. They can be accessed and manipulated using various methods.
241+
- Access Methods:
242+
- Indexing: Access individual characters using their indices.
243+
```python
244+
my_string = "Hello"
245+
print(my_string[0]) # Output: H
246+
```
247+
- Slicing: Extract substrings using slicing notation.
248+
```python
249+
my_string = "Hello"
250+
print(my_string[1:3]) # Output: el
251+
```
252+
- String Methods: Python provides numerous methods to manipulate strings such as `upper()`, `lower()`, `split()`, `join()`, `strip()`, `replace()`, etc.
253+
```python
254+
my_string = "Hello, world"
255+
print(my_string.upper()) # Output: HELLO, WORLD
256+
```
257+
- String Formatting: Strings support various formatting options such as `%` formatting, `str.format()`, and f-strings (formatted string literals).
258+
```python
259+
name = "John"
260+
age = 30
261+
print("My name is %s and I am %d years old." % (name, age))
262+
print("My name is {} and I am {} years old.".format(name, age))
263+
print(f"My name is {name} and I am {age} years old.")
264+
```
265+
- String Concatenation: Combine strings using the `+` operator or the `join()` method for efficiency.
266+
```python
267+
str1 = "Hello"
268+
str2 = "world"
269+
concatenated_str = str1 + ", " + str2
270+
efficient_concatenation = ", ".join([str1, str2])
271+
```
272+
- String Interpolation: Embed expressions within strings using f-strings or the `format()` method.
273+
```python
274+
price = 10
275+
quantity = 5
276+
print(f"Total cost: ${price * quantity}")
277+
print("Total cost: ${}".format(price * quantity))
278+
```
279+
- String Operations: Strings support operations such as concatenation (`+`), repetition (`*`), membership (`in`), and length (`len()`).
280+
```python
281+
str1 = "Hello"
282+
str2 = "world"
283+
concatenated_str = str1 + " " + str2
284+
print(len(concatenated_str)) # Output: 11
285+
```
286+
- Escape Characters: Use escape characters such as `\n` (newline), `\t` (tab), and `\\` (backslash) to include special characters in strings.
287+
```python
288+
print("Hello\nworld")
289+
print("This is a\ttab")
290+
print("C:\\path\\to\\file")
291+
```
292+
127293

128294
## Difference between Data Structures:
129295

0 commit comments

Comments
 (0)