Python array मॉड्यूल
In this page:
from array import array
array_name = array("type_code", [item1, item2])
array मॉड्यूल क्या है?
Built-in array मॉड्यूल एक compact, type-constrained sequence देता है, जबकि Python की साधारण list एक ही container में integers, strings, और objects को आज़ादी से मिला सकती है।
array.array के हर element को एक ही declared type साझा करना पड़ता है, जिससे यह data को memory में ज़्यादा compact तरीके से store कर सकता है।
उदाहरण: What Is the array Module?
import array
arr = array.array("i", [1, 2, 3]) # "i" means every element is a signed int
print(arr)
एक Typed Array बनाना
आप इसे array.array(typecode, values) से बनाते हैं, जहाँ typecode एक single character होता है जैसे signed int के लिए i या double-precision float के लिए d, जो पहले ही declare कर दिया जाता है और हर insertion पर enforce होता है।
गलत type की value जोड़ने की कोशिश करने पर तुरंत TypeError raise होता है, जबकि एक list इसे चुपचाप स्वीकार कर लेती।
उदाहरण: Creating a Typed Array
import array
arr = array.array("d", [1.5, 2.5]) # "d" means every element is a double-precision float
try:
arr.append("not a float") # wrong type, rejected immediately
except TypeError as e:
print("Error:", e)
array बनाम list
एक साधारण list ज़्यादा flexible है और लगभग हमेशा सही default choice होती है, लेकिन बड़ी संख्या में एक ही type की numeric values store करते समय array काफी कम memory इस्तेमाल करता है, क्योंकि यह हर element के लिए पूरे Python objects store करने का overhead टाल देता है।
इसे memory-constrained numeric-heavy code में इस्तेमाल करें, list के general replacement के तौर पर नहीं।
उदाहरण: array vs list
import array
import sys
arr = array.array("i", [1, 2, 3])
lst = [1, 2, 3]
print(sys.getsizeof(arr) < sys.getsizeof(lst)) # array uses less memory for same-typed numbers
array बनाम NumPy
यह built-in array मॉड्यूल NumPy के ndarray जैसा नहीं है, जिसे इस site पर कहीं और cover किया गया है — NumPy एक अलग third-party library है जो vectorized math operations, multi-dimensional shapes, और broadcasting देती है जो standard-library array मॉड्यूल बिल्कुल नहीं देता।
array एक हल्का stdlib tool है, NumPy एक पूरी numerical computing library है।
उदाहरण: array vs NumPy
import array
arr = array.array("i", [1, 2, 3])
print(type(arr))
# NumPy's ndarray adds vectorized math and multi-dimensional shapes on top of this
आम array Operations
Arrays ज़्यादातर list-जैसे operations support करते हैं — indexing, slicing, append(), iteration — साथ ही कुछ array-specific भी, जैसे raw byte representation में बदलने के लिए tobytes(), जो binary file formats या packed numeric data expect करने वाले C-level APIs से जुड़ते समय उपयोगी है।
उदाहरण: Common array Operations
import array
arr = array.array("i", [1, 2, 3])
arr.append(4) # list-like operation
print(arr[1:3]) # slicing works like a list
print(arr.tobytes()) # raw byte representation for binary interop
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: