If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
Basically tuple multiple values को store करने के लिए use किये जाते हैं। multiple values को एक साथ tuple में रखना packing कहलाता है जबकि उन values को एक एक करके किसी variable में निकलना tuple unpacking कहते हैं।
tuple में जितनी values हैं , उतने variables को directly हम tuple से extract कर सकते हैं।
t = ('Rahul Kumar', 24, 'India')
name, age, country = t
print('Name :', name)
print('Age :', age)
print('Country :', country)
C:\Users\Rahulkumar\Desktop\python>python tuple_unpack.py Name : Rahul Kumar Age : 24 Country : India
Note :variables की सख्या tuple में stored values के बराबर ही होनी चाहिए , नहीं तो error आ जयगी।
t = ('Rahul Kumar', 24, 'India') name, age = t #It raise an error : ValueError: too many values to unpack (expected 2)
अब अगर आप कुछ variables निकलना ही चाहते हैं तो आपको asterisk ( * ) का use करना पड़ेगा , इससे जितने variables होंगे उतनी values उन variables में निकल बाकी बची हुई values asterisk ( * ) के साथ defined variable में आ जायँगी।
See Example -
t = ('Rahul Kumar', 24, 'Agra', 'UP', 'India')
name, age, city, *other = t
print('Name :', name)
print('Age :', age)
print('City :', city)
print('Other :', other)
C:\Users\Rahulkumar\Desktop\python>python tuple_unpack.py Name : Rahul Kumar Age : 24 City : Agra Other : ['UP', 'India']
( * ) की help से आप starting values के अलावा last / mid कहीं के values को variable में easily extract कर सकते हो।
t = ('Rahul Kumar', 24, 'Agra', 'UP', 'India')
name, *other, country = t
print('Name :', name)
print('Other :', other)
print('Country :', country)
C:\Users\Rahulkumar\Desktop\python>python tuple_unpack.py Name : Rahul Kumar Other : [24, 'Agra', 'UP'] Country : India
ऐसा नहीं कि आप tuple को ही unpack कर सकते हैं , इसी तरह से आप list को भी unpack करके किसी particular value को extract कर सकते हैं।
तो कुछ इस तरह से tuple से किसी particular value को variable में easily extract कर सकते हैं। I Hope, आपको tuple unpacking अच्छे से समझ आया होगा।
Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)
Get connected with me. :) LinkedIn Twitter Instagram Facebook