Python में set भी 4 built in data types (list , tuple , set , dictionary) में से एक है जिसका use data collections को store करने किया जाता है। data collections means एक values का collection या कह सकते हैं multiple values store करता है।


Python set items Unchangeable, Unordered, Unindexed & unique होते हैं।

  1. Unordered - मतलब जिस order में हमने items को set में insert किया था जरूरी नहीं कि हमें उसी order में मिलें हर बार अलग - अलग order हो सकता है।

  2. Unique - means duplicate items को insert नहीं कर सकते हैं , और अगर same values रखते भी हैं तो भी एक ही value accept होगी।

  3. Unchangeable - मतलब उन items को जरूरत पड़ने पर update / delete नहीं कर सकते हैं , हाँ या set में नए items को add जरूर कर सकते हैं।

  4. Unindexed - मतलब list और tuple की तरह item का कोई index number नहीं होता है , इसलिए हम index number से item access नही कर सकते हैं।


Python में set हम curly braces { } use करके create कर सकते हैं -

s1 = {12,34,56,67}
s2 = {True, 'Name', 56.7, 56}

Python set Example

Copy Fullscreen Close Fullscreen Run
s = {True, 'Name', 56.7, 56}
print(s)

Note : यह जरूरी नहीं है कि set में सिर्फ same type ही items हों , आप अपनी need के according किसी भी type (String , Boolean , Numeric) के elements insert कर सकते हैं।

Python set len() & type()

set की length जानने के लिए len() function का use किया जाता है और , type जानने के लिए type() function का use किया जाता है।

Copy Fullscreen Close Fullscreen Run
s = {True, 'Name', 56.7, 56}
print('Set Length :', len(s))
print('Type :', type(s))
Output
C:\Users\Rahulkumar\Desktop\python>python set_len_type.py
Set Length : 4
Type : <class 'set'> 

Python Iterating set using for Loop

हालाँकि set items unindexed होते हैं लेकिन फिर भी इसे हम for loop की help से iterate कर सकते हैं।

Copy Fullscreen Close Fullscreen Run
s = {True, 'Shyama', 56.7, 56}
print('Iterate using for loop :')
for item in s :
	print(item)
Output
C:\Users\Rahulkumar\Desktop\python>python set_iterate.py
Iterate using for loop :
56
True
56.7
Shyama

example में आप देख सकते हैं कि items का order वैसा नहीं है जिस order में रखे गए थे , अगर आप बार - बार इसी program को run करोगे तो इनका order भी change होता रहेगा।


अब अगर आप duplicate items रखते भी होतो insert सिर्फ एक ही होगा।

Copy Fullscreen Close Fullscreen Run
#here 12, 67, and 89 are duplicate.
s = {12,45,67,78,89,23,12,67,89}
print(s)
Output
C:\Users\Rahulkumar\Desktop\python>python set_ex.py
{67, 12, 45, 78, 23, 89}

I Hope, अब आप समझ गए होंगे कि set list और tuple से कितना different है।

Related Topics :

Rahul Kumar

Rahul Kumar

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

b2eprogrammers