इस पोस्ट में, हम Python में list और tuple के अंतर को समझेंगे।
List और tuple Python में उपयोग की जाने वाली दो अलग-अलग प्रकार की data structures हैं। वे दोनों अलग-अलग instances में अलग-अलग प्रकार के data store करने के लिए उपयोग किए जाते हैं।
List
इसे अक्सर sequence के रूप में refer किया जाता है। इसे सबसे frequently used data types में से एक माना जाता है, साथ ही इसकी versatility के लिए सराहा जाता है। List को square brackets ([ ]) के अंदर सभी elements रखकर और elements को commas से अलग करके बनाया जा सकता है। List के अंदर किसी भी संख्या में elements हो सकते हैं और वे अलग-अलग types के भी हो सकते हैं (जैसे integer, float, string, आदि)। List की सबसे महत्वपूर्ण विशेषता यह है कि यह एक mutable structure है, यानी list को reference करके changes किए जा सकते हैं।
आइए देखें कि heterogeneous data types के साथ list कैसे बनाई जा सकती है:
उदाहरण
my_list = [1.8, 'string', 34, 'a'] print(my_list)
आउटपुट
[1.8, 'string', 34, 'a']
List के अंदर data को access करने के कई तरीके हैं।
आइए देखें कि indexing का उपयोग करके elements कैसे access किए जा सकते हैं:
उदाहरण
my_list = [1.8, 'string', 34, 'a']
print("The second element is")
print(my_list[1])
आउटपुट
The second element is string
हम एक range से दूसरी range तक elements access कर सकते हैं। इसे list slicing के रूप में जाना जाता है। आइए देखें कि यह कैसे किया जा सकता है:
उदाहरण
my_list = [1.8, 'string', 34, 'a']
print("The elements within a certain range are")
print(my_list[1:4])
आउटपुट
The elements within a certain range are ['string', 34, 'a']
हम indexing perform करके और उस index पर new value assign करके list के values बदल सकते हैं। आइए देखें कि यह कैसे किया जा सकता है:
उदाहरण
my_list = [1.8, 'string', 34, 'a']
print("List before changes")
print(my_list)
my_list[1] = 'my_string'
print("List after changes")
print(my_list)
आउटपुट
List before changes [1.8, 'string', 34, 'a'] List after changes [1.8, 'my_string', 34, 'a']
Tuple
अब आइए tuple structure के working को समझते हैं। यह parenthesis का उपयोग करके बनाया जाता है, यानी ()। Tuple की महत्वपूर्ण विशेषता यह है कि यह immutable है, यानी tuple के अंदर assign किए गए elements को tuple access करके बदला नहीं जा सकता। Tuple के अंदर किसी भी संख्या में elements हो सकते हैं और वे अलग-अलग types के भी हो सकते हैं (जैसे integer, float, string, आदि)।
नोट: Tuple को parenthesis के उपयोग के बिना भी बनाया जा सकता है, लेकिन parenthesis का उपयोग करना good practice माना जाता है।
आइए देखें कि single element के साथ tuple कैसे बनाया जा सकता है:
उदाहरण
my_tuple = ("hey",)
print("Creating a tuple with one element")
print(my_tuple)
आउटपुट
("hello")
नोट: Tuple के elements access करना, negative indexing, और list slicing list के समान ही हैं।
यदि tuple के अंदर एक list है, तो उस list को बदला जा सकता है, लेकिन जो elements केवल tuple के अंदर हैं, list के अंदर नहीं, उन्हें बदला नहीं जा सकता।