Code Explanation:
๐น 1. Importing the array Class
from array import array
✅ Explanation
array is imported from Python's built-in array module.
Unlike a Python list, an array stores only one data type.
Arrays are faster and use less memory when storing large amounts of numeric data.
Current Situation
array module
↓
array class ready to use
๐น 2. Creating an Integer Array
nums = array("i", [5, 10])
✅ Explanation
Here Python creates an integer array.
Syntax:
array(typecode, iterable)
Here,
"i" → Integer type
[5, 10] → Initial values
Current Memory
nums
↓
array('i', [5, 10])
Visual Representation
Index
0 1
↓
5 10
๐น 3. Understanding the Type Code
"i"
✅ Explanation
The type code tells Python what type of values the array can store.
Common type codes:
Type Code Meaning
"i" Integer
"f" Float
"d" Double
"u" Unicode Character
Since the type is "i":
✔ 5
✔ 10
✔ 15
❌ "Python"
❌ 5.5
Only integers are allowed.
๐น 4. Calling extend()
nums.extend([15, 20])
✅ Explanation
extend() adds multiple elements to the end of the array.
Unlike append(), which adds one element, extend() adds all elements from an iterable.
Before:
[5, 10]
Values to add:
15
20
๐น 5. How extend() Works Internally
Python takes every element one by one.
Internally it behaves almost like this:
nums.append(15)
nums.append(20)
Step 1
[5,10]
↓
append(15)
↓
[5,10,15]
Step 2
[5,10,15]
↓
append(20)
↓
[5,10,15,20]
Current Memory
nums
↓
array('i',[5,10,15,20])
๐น 6. Calling tolist()
nums.tolist()
✅ Explanation
An array is not a Python list.
tolist() converts the array into a normal list.
Before conversion
array('i',[5,10,15,20])
After conversion
[5,10,15,20]
Only the data structure changes.
The values remain exactly the same.
๐น 7. Printing the Result
print(nums.tolist())
✅ Explanation
Python prints the converted list.
Output
[5, 10, 15, 20]
๐ฏ Final Output
[5, 10, 15, 20]

0 Comments:
Post a Comment