स्ट्रिंग्स की एक सूची दी गई है, आइए पहला गैर-खाली तत्व ढूंढते हैं। चुनौती यह है कि सूची की शुरुआत में एक, दो या कई खाली स्ट्रिंग्स हो सकती हैं और हमें गतिशील रूप से पहली गैर-खाली स्ट्रिंग ढूंढनी है।
next के साथ
यदि वर्तमान तत्व null है तो अगले तत्व पर जाने के लिए हम next फ़ंक्शन लागू करते हैं।
उदाहरण
listA = ['','top', 'pot', 'hot', ' ','shot']
# दी गई सूची
print("Given list:\n ",listA)
# next() का उपयोग करके
res = next(sub for sub in listA if sub)
# परिणाम प्रिंट करें
print("The first non empty string is : \n",res)
आउटपुट
Given list: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
filter के साथ
हम filter शर्त का उपयोग करके भी इसे प्राप्त कर सकते हैं। filter शर्त null मान को हटा देगी और हम पहला non-null मान चुनेंगे। केवल पायथन 2 के साथ।
उदाहरण
listA = ['','top', 'pot', 'hot', ' ','shot']
# दी गई सूची
print("Given list:\n ",listA)
# filter() का उपयोग करके
res = filter(None, listA)[0]
# परिणाम प्रिंट करें
print("The first non empty string is : \n",res)
आउटपुट
Given list: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top