ऐर

ऐरे में Python

96 अभ्यास

ऐरे के बारे में

एक list क्रम में रखी गई वस्तुओं का एक परिवर्तनीय संग्रह है। अधिकांश संग्रहों की तरह (देखें बिल्ट-इन tuple, dict और set), ऐरे किसी भी (या कई) डेटा टाइप का संदर्भ रख सकते हैं - जिसमें अन्य ऐरे भी शामिल हैं। किसी भी sequence की तरह, वस्तुओं को बाईं ओर से 0-based index संख्या और दाईं ओर से -1-based index के ज़रिए एक्सेस किया जा सकता है। ऐरे को पूर्ण रूप से या आंशिक रूप से slice notation या <list>.copy() के ज़रिए कॉपी किया जा सकता है।

ऐरे common और mutable दोनों तरह के सीक्वेंस ऑपरेशन का समर्थन करते हैं, जैसे min()/max(), <list>.index(), .append() और .reverse()। ऐरे के एलिमेंट्स को for item in <list> कंस्ट्रक्ट का उपयोग करके इटरेट किया जा सकता है। जब एलिमेंट का इंडेक्स और एलिमेंट की वैल्यू दोनों की आवश्यकता हो, तो for index, item in enumerate(<list>) का उपयोग किया जा सकता है।

ऐरे dynamic arrays के रूप में लागू किए जाते हैं, जो Java के Arraylist टाइप के समान हैं। इनका उपयोग अक्सर अज्ञात लंबाई (एंट्रीज़ की संख्या मनमाने ढंग से बढ़ या घट सकती है) के समान डेटा (स्ट्रिंग्स, संख्याएँ, सेट्स आदि) के समूहों को संग्रहीत करने के लिए किया जाता है।

एलिमेंट्स को एक्सेस करना, in के ज़रिए मेंबरशिप की जाँच करना, या ऐरे के "दाईं ओर" वस्तुओं को जोड़ना, ये सब बहुत कुशल हैं। प्रीपेंडिंग ("बाईं ओर" जोड़ना) या ऐरे के बीच में इन्सर्ट करना बहुत कम कुशल है क्योंकि उन ऑपरेशन्स में एलिमेंट्स को क्रम में बनाए रखने के लिए शिफ्ट करना पड़ता है। एक समान डेटा स्ट्रक्चर के लिए जो दोनों ओर से मेमोरी-कुशल appends/pops का समर्थन करता है, collections.deque देखें, जिसका प्रदर्शन दोनों दिशाओं में लगभग समान O(1) है।

क्योंकि ऐरे परिवर्तनीय होते हैं और मनमाने Python ऑब्जेक्ट्स के संदर्भ रख सकते हैं, वे समान दिखने वाली लंबाई के array.array या tuple (जो अपरिवर्तनीय है) की तुलना में मेमोरी में अधिक जगह लेते हैं। फिर भी, ऐरे एक अत्यंत लचीला और उपयोगी डेटा स्ट्रक्चर हैं और Python में कई बिल्ट-इन मेथड्स और ऑपरेशन्स अपने आउटपुट के रूप में ऐरे उत्पन्न करते हैं।

निर्माण

एक list को चौकोर [] ब्रैकेट और एलिमेंट्स के बीच कॉमा के साथ लिटरल के रूप में घोषित किया जा सकता है:

>>> no_elements = []

>>> no_elements
[]

>>> one_element = ["Guava"]

>>> one_element
['Guava']

>>> elements_separated_with_commas = ["Parrot", "Bird", 334782]

>>> elements_separated_with_commas
['Parrot', 'Bird', 334782]

पठनीयता के लिए, जब किसी ऐरे में बहुत सारे एलिमेंट्स या नेस्टेड डेटा स्ट्रक्चर्स हों, तो लाइन ब्रेक का उपयोग किया जा सकता है:

>>> lots_of_entries = [
...    "Rose",
...    "Sunflower",
...    "Poppy",
...    "Pansy",
...    "Tulip",
...    "Fuchsia",
...    "Cyclamen",
...    "Lavender"
... ]

>>> lots_of_entries
['Rose', 'Sunflower', 'Poppy', 'Pansy', 'Tulip', 'Fuchsia', 'Cyclamen', 'Lavender']


# Each data structure is on its own line to help clarify what they are.
>>> nested_data_structures = [
...    {"fish": "gold", "monkey": "brown", "parrot": "grey"},
...    ("fish", "mammal", "bird"),
...    ['water', 'jungle', 'sky']
... ]

>>> nested_data_structures
[{'fish': 'gold', 'monkey': 'brown', 'parrot': 'grey'}, ('fish', 'mammal', 'bird'), ['water', 'jungle', 'sky']]

list() कंस्ट्रक्टर को खाली या एक iterable को आर्गुमेंट के रूप में उपयोग किया जा सकता है। कंस्ट्रक्टर द्वारा इटरेबल के एलिमेंट्स को एक-एक करके लिया जाता है और क्रम में ऐरे में जोड़ा जाता है:

>>> no_elements = list()
>>> no_elements
[]

# The tuple is unpacked and each element is added.
>>> multiple_elements_from_tuple = list(("Parrot", "Bird", 334782))

>>> multiple_elements_from_tuple
['Parrot', 'Bird', 334782]

# The set is unpacked and each element is added.
>>> multiple_elements_from_set = list({2, 3, 5, 7, 11})

>>> multiple_elements_from_set
[2, 3, 5, 7, 11]

स्ट्रिंग या डिक्शनरी के साथ लिस्ट कंस्ट्रक्टर का उपयोग करने पर परिणाम चौंकाने वाले हो सकते हैं:

# String elements (Unicode code points) are iterated through and added *individually*.
>>> multiple_elements_string = list("Timbuktu")

>>> multiple_elements_string
['T', 'i', 'm', 'b', 'u', 'k', 't', 'u']

# Unicode separators and positioning code points are also added *individually*.
>>> multiple_code_points_string = list('अभ्यास')

>>> multiple_code_points_string
['अ', 'भ', '्', 'य', 'ा', 'स']

# The iteration default for dictionaries is over the keys, so only key data is inserted into the list.
>>> source_data = {"fish": "gold", "monkey": "brown"}
>>> list(source_data)
['fish', 'monkey']

चूँकि list() कंस्ट्रक्टर केवल इटरेबल्स (या कुछ नहीं) को आर्गुमेंट्स के रूप में लेता है, जो ऑब्जेक्ट्स इटरेबल नहीं हैं वे TypeError उठाएँगे। इसलिए, लिटरल विधि के ज़रिए एक-आइटम वाली लिस्ट बनाना बहुत आसान है।

# Numbers are not iterable, and so attempting to create a list with a number passed to the constructor fails.
>>> one_element = list(16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

# Tuples *are* iterable, so passing a one-element tuple to the constructor does work, but it's awkward
>>> one_element_from_iterable = list((16,))

>>> one_element_from_iterable
[16]

एलिमेंट्स को एक्सेस करना

ऐरे के अंदर की वस्तुओं (साथ ही अन्य सीक्वेंस टाइप्स जैसे str और tuple के एलिमेंट्स) को ब्रैकेट नोटेशन का उपयोग करके एक्सेस किया जा सकता है। इंडेक्स left --> right (शून्य से शुरू) या right --> left (-1 से शुरू) हो सकते हैं।

बाईं ओर से इंडेक्स ⟹






0
👇🏾
1
👇🏾
2
👇🏾
3
👇🏾
4
👇🏾
5
👇🏾
P y t h o n
👆🏾
-6
👆🏾
-5
👆🏾
-4
👆🏾
-3
👆🏾
-2
👆🏾
-1





⟸ दाईं ओर से इंडेक्स
>>> breakfast_foods = ["Oatmeal", "Fruit Salad", "Eggs", "Toast"]

# Oatmeal is at index 0 or index -4.
>>> breakfast_foods[0]
'Oatmeal'

>>> breakfast_foods[-4]
'Oatmeal'

# Eggs are at index -2 or 2
>>> breakfast_foods[-2]
'Eggs'

>>> breakfast_foods[2]
'Eggs'

# Toast is at -1
>>> breakfast_foods[-1]
'Toast'

ऐरे के एक हिस्से को slice notation (<list>[<start>:<stop>]) के ज़रिए एक्सेस किया जा सकता है। एक slice को स्थिति index पर एलिमेंट सीक्वेंस के रूप में परिभाषित किया जाता है, जिसमें start <= index < stop होता है। Slicing "स्लाइस किए गए" आइटम्स की एक कॉपी लौटाता है और मूल list को संशोधित नहीं करता।

स्लाइस में एक step पैरामीटर का भी उपयोग किया जा सकता है (<list>[<start>:<stop>:<step>]) ताकि लौटाए गए एलिमेंट्स को "स्किप" या फ़िल्टर किया जा सके (उदाहरण के लिए, step का मान 2 होने पर सेक्शन में हर दूसरा एलिमेंट चुना जाएगा):

>>> colors = ["Red", "Purple", "Green", "Yellow", "Orange", "Pink", "Blue", "Grey"]

# If there is no step parameter, the step is assumed to be 1.
>>> middle_colors = colors[2:6]

>>> middle_colors
['Green', 'Yellow', 'Orange', 'Pink']

# If the start or stop parameters are omitted, the slice will
# start at index zero, and will stop at the end of the list.
>>> primary_colors = colors[::3]

>>> primary_colors
['Red', 'Yellow', 'Blue']

ऐरे के साथ काम करना

ऐरे एक iterator प्रदान करते हैं, और इन्हें अन्य सीक्वेंस टाइप्स की तरह ही for item in <list> या for index, item in enumerate(<list>) का उपयोग करके लूप किया जा सकता है:

# Make a list, and then loop through it to print out the elements
>>> colors = ["Orange", "Green", "Grey", "Blue"]
>>> for item in colors:
...     print(item)

Orange
Green
Grey
Blue


# Print the same list, but with the indexes of the colors included
>>> colors = ["Orange", "Green", "Grey", "Blue"]
>>> for index, item in enumerate(colors):
...     print(item, ":", index)

Orange : 0
Green : 1
Grey : 2
Blue : 3


# Start with a list of numbers and then loop through and print out their cubes.
>>> numbers_to_cube = [5, 13, 12, 16]
>>> for number in numbers_to_cube:
...     print(number**3)

125
2197
1728
4096

वैल्यू की लिस्ट बनाने का एक आम तरीका लूप के अंदर <list>.append() का उपयोग करना है:

>>> cubes_to_1000 = []
>>> for number in range(11):
...    cubes_to_1000.append(number**3)

>>> cubes_to_1000
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

ऐरे को विभिन्न तकनीकों के माध्यम से भी जोड़ा जा सकता है:

# Using the plus + operator unpacks each list and creates a new list, but it is not efficient.
>>> new_via_concatenate = ["George", 5] + ["cat", "Tabby"]

>>> new_via_concatenate
['George', 5, 'cat', 'Tabby']

# Likewise, using the multiplication operator * is the equivalent of using + n times.
>>> first_group = ["cat", "dog", "elephant"]
>>> multiplied_group = first_group * 3

>>> multiplied_group
['cat', 'dog', 'elephant', 'cat', 'dog', 'elephant', 'cat', 'dog', 'elephant']

# Another method for combining 2 lists is to use slice assignment or a loop-append.
# This assigns the second list to index 0 in the first list.
>>> first_one = ["cat", "Tabby"]
>>> second_one = ["George", 5]
>>> first_one[0:0] = second_one

>>> first_one
['George', 5, 'cat', 'Tabby']

# This loops through the first list and appends its items to the end of the second list.
>>> first_one = ["cat", "Tabby"]
>>> second_one = ["George", 5]

>>> for item in first_one:
...      second_one.append(item)

>>> second_one
['George', 5, 'cat', 'Tabby']

कुछ सावधानियाँ

याद रखें कि Python में वेरिएबल्स लेबल्स होते हैं जो अंतर्निहित ऑब्जेक्ट्स की ओर इशारा करते हैं। lists एक और परत जोड़ते हैं, कंटेनर ऑब्जेक्ट्स के रूप में। वे अपने एकत्रित आइटम्स के लिए ऑब्जेक्ट संदर्भ रखते हैं। यदि ठीक से संभाला न जाए, तो यह ऐरे के साथ काम करते समय कई संभावित समस्याएँ पैदा कर सकता है।

एक से अधिक वेरिएबल नाम असाइन करना

एक list ऑब्जेक्ट को नए वेरिएबल नाम को असाइन करने पर न तो list ऑब्जेक्ट कॉपी होता है और न ही उसके एलिमेंट्स। नए नाम के तहत list के एलिमेंट्स में किया गया कोई भी बदलाव मूल को प्रभावित करता है।

list.copy() या स्लाइस के ज़रिए shallow_copy बनाने से यह पहले स्तर की संदर्भ जटिलता टल जाएगी। एक shallow_copy एक नया list ऑब्जेक्ट बनाएगा, लेकिन अंदर मौजूद लिस्ट एलिमेंट्स के लिए नए ऑब्जेक्ट नहीं बनाएगा। इस प्रकार की कॉपी आमतौर पर आपके लिए दोनों list ऑब्जेक्ट्स से स्वतंत्र रूप से आइटम्स जोड़ने या हटाने के लिए पर्याप्त होगी, और प्रभावी रूप से आपके पास दो "अलग" लिस्ट्स होंगी।

>>> actual_names = ["Tony", "Natasha", "Thor", "Bruce"]

# Assigning a new variable name does not make a copy of the container or its data.
>>> same_list = actual_names

#  Altering the list via the new name is the same as altering the list via the old name.
>>> same_list.append("Clarke")
["Tony", "Natasha", "Thor", "Bruce", "Clarke"]

>>> actual_names
["Tony", "Natasha", "Thor", "Bruce", "Clarke"]

#  Likewise, altering the data in the list via the original name will also alter the data under the new name.
>>> actual_names[0] = "Wanda"
['Wanda', 'Natasha', 'Thor', 'Bruce', 'Clarke']

# If you copy the list, there will be two separate list objects which can be changed independently.
>>> copied_list = actual_names.copy()
>>> copied_list[0] = "Tony"

>>> actual_names
['Wanda', 'Natasha', 'Thor', 'Bruce', 'Clarke']

>>> copied_list
["Tony", "Natasha", "Thor", "Bruce", "Clarke"]

यह संदर्भ जटिलता नेस्टेड या मल्टीप्लाइड लिस्ट्स के साथ काम करते समय और बढ़ जाती है (निम्नलिखित उदाहरण 2013 के उत्कृष्ट Ned Batchelder ब्लॉग पोस्ट Names and values: making a game board से हैं):

from pprint import pprint

# This will produce a game grid that is 8x8, pre-populated with zeros.
>>> game_grid = [[0]*8]*8

>>> pprint(game_grid)
[[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0]]

# An attempt to put a "X" in the bottom right corner.
>>> game_grid[7][7] = "X"

# This attempt doesn't work because all the rows are referencing the same underlying list object.
>>> pprint(game_grid)
[[0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X'],
 [0, 0, 0, 0, 0, 0, 0, 'X']]

लेकिन इस स्थिति में, हम जैसा व्यवहार चाहते हैं उसके लिए एक shallow_copy पर्याप्त है:

from pprint import pprint

# This loop will safely produce a game grid that is 8x8, pre-populated with zeros
>>> game_grid = []
>>> filled_row = [0] * 8
>>> for row in range(8):
...    game_grid.append(filled_row.copy()) # This is making a new shallow copy of the inner list object each iteration.

>>> pprint(game_grid)
[[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0]]

# An attempt to put a "X" in the bottom right corner.
>>> game_grid[7][7] = "X"

# The game grid now works the way we expect it to!
>>> pprint(game_grid)
[[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 'X']]

जैसा कि पहले उल्लेख किया गया है, ऐरे संदर्भों के कंटेनर होते हैं, इसलिए संभावित जटिलता की दूसरी परत होती है। यदि किसी ऐरे में वेरिएबल्स, ऑब्जेक्ट्स, या नेस्टेड डेटा स्ट्रक्चर्स हैं, तो वे दूसरे स्तर के संदर्भ shallow_copy या स्लाइस के ज़रिए कॉपी नहीं किए जाएँगे। अंतर्निहित ऑब्जेक्ट्स को म्यूटेट करने पर किसी भी और सभी कॉपी पर प्रभाव पड़ेगा, क्योंकि प्रत्येक list ऑब्जेक्ट में केवल अंदर मौजूद एलिमेंट्स की ओर इशारा करने वाले संदर्भ होते हैं।

from pprint import pprint

>>> pprint(game_grid)
[[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 'X']]

# We'd like a new board, so we make a shallow copy.
>>> new_game_grid = game_grid.copy()

# But a shallow copy doesn't copy the contained references or objects.
>>> new_game_grid[0][0] = 'X'

# So changing the items in the copy also changes the originals items.
>>>  pprint(game_grid)
[['X', 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 'X']]

संबंधित डेटा टाइप्स

ऐरे अक्सर स्टैक्स और क्यूज़ के रूप में उपयोग किए जाते हैं, हालाँकि उनका अंतर्निहित कार्यान्वयन प्रीपेंडिंग और इन्सर्टिंग को धीमा बनाता है। collections मॉड्यूल एक deque वेरिएंट प्रदान करता है जो तेज़ एपेंड्स और पॉप्स के लिए अनुकूलित है, जो doubly linked list के रूप में लागू किया गया है। नेस्टेड लिस्ट्स का उपयोग छोटे मैट्रिक्स को मॉडल करने के लिए भी किया जाता है, हालाँकि Numpy और Pandas लाइब्रेरीज़ कुशल मैट्रिक्स और टेबुलर डेटा मैनिपुलेशन के लिए अधिक मजबूत हैं। collections मॉड्यूल एक UserList टाइप भी प्रदान करता है जिसे विशेष लिस्ट आवश्यकताओं के अनुरूप अनुकूलित किया जा सकता है।

GitHub के ज़रिए संपादित करें यह लिंक नई विंडो या टैब में खुलता है।

ऐरे सीखिए

अभ्यास लॉक है

ऐरे पर अभ्यास करने के लिए 5 और अभ्यास अनलॉक कीजिए