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 type of data.
Arrays are more memory-efficient than lists when storing many numbers.
Think of an array as a train where every compartment must carry the same type of passenger.
Python List
↓
Can Store
1
"Python"
5.5
Array
↓
Can Store
Only One Data Type
๐น 2. Creating an Integer Array
nums = array('i', [1, 2, 3])
✅ Explanation
Here Python creates an array.
Syntax:
array(typecode, iterable)
There are two parts:
Type Code
'i'
means
Signed Integer
Common type codes:
Type Code Meaning
'i' Integer
'f' Float
'd' Double
'u' Unicode Character
The second argument is
[1, 2, 3]
These values are copied into the array.
Current memory:
nums
↓
array('i',[1,2,3])
๐น 3. Understanding the Array
Current array:
Index
0 1 2
↓
1 2 3
Unlike a list,
array('i')
cannot store:
"Hello"
or
5.5
because every element must be an integer.
๐น 4. Appending a New Value
nums.append(4)
✅ Explanation
append() adds a new element at the end of the array.
Before:
array('i')
↓
1
2
3
After appending:
array('i')
↓
1
2
3
4
Current memory:
nums
↓
array('i',[1,2,3,4])
๐น 5. Calling tolist()
nums.tolist()
✅ Explanation
An array object is not a normal Python list.
The tolist() method converts the array into a standard Python list.
Before conversion:
array
↓
array('i',[1,2,3,4])
After conversion:
List
↓
[1,2,3,4]
No values change—only the data structure changes.
๐น 6. Printing the List
print(nums.tolist())
✅ Explanation
Python prints the converted list.
Output:
[1, 2, 3, 4]
๐ฏ Final Output
[1, 2, 3, 4]

0 Comments:
Post a Comment