
👉Python Array – Definition and Creation
👉What is a Python Array?
A Python Array is a data structure that holds multiple elements of the same data type. It is used to store collections of data efficiently. Python arrays are managed using the “array” module. When using this module, all elements must have the same numeric type.
👉When to Use Arrays in Python
Python arrays are ideal when you need to manage multiple variables of the same type. They are faster and consume less memory than lists, making them suitable for handling large data collections.
👉Syntax to Create an Array in Python
import array as myarray
array_name = myarray.array(type_code, [elements])
👉Example:
import array as myarray
abc = myarray.array(‘d’, [2.5, 4.9, 6.7])
print(abc)
👉 Type Codes
Type Code | Python Type | C Type | Size (Bytes) |
‘u’ | Unicode Character | Py_UNICODE | 2 |
‘b’ | Int (Signed Char) | Signed Char | 1 |
‘B’ | Int (Unsigned Char) | Unsigned Char | 1 |
‘h’ | Int (Signed Short) | Signed Short | 2 |
‘f’ | Float | Float | 4 |
‘d’ | Float | Double | 8 |
👉Accessing Array Elements
Access elements using their index:
import array
balance = array.array(‘i’, [300, 200, 100])
print(balance[1])
# Output: 200
👉Access the First and Last Element
print(abc[0]) # First element
print(abc[-1]) # Last element
👉Using Slice Operation
print(abc[1:4])
print(abc[7:10])
👉Inserting Elements in Array
balance.insert(2, 150)
print(balance) # Output: [300, 200, 150, 100]
👉Modifying Array Elements
a[0] = 999
print(a)
👉Concatenating Arrays
numbers = first + second
print(numbers)
👉Deleting Elements from Array
Using pop() or del:
first.pop(2)
del no[4]
print(no)
👉Searching Array Elements
print(number.index(3)) # Output: 1
👉Reversing an Array
number.reverse()
print(number) # Output: [3, 2, 1]
👉Converting Array to Unicode
from array import array
p = array(‘u’, [u’\u0050′, u’\u0059′, u’\u0054′])
print(p)
👉Counting Array Elements
print(number.count(3)) # Output: 4
👉Traversing Arrays
for x in balance:
print(x)
👉Summary
- Python arrays provide an efficient way to manage collections of similar data types.
- Use the array module for creating and manipulating arrays in Python.
- Arrays are mutable and support various operations like insertion, deletion, and concatenation.
- Knowing Python array syntax and methods ensures efficient data handling for better programming practices.