What Are Data Types ?
Programming ki duniya mein sab kuch data hi hai—chahe wo kisi user ka naam ho, unka phone number ho, ya kisi game ka score. Lekin computer ko apne aap yeh nahi pata hota ki 10 ek number hai aur "Amit" ek naam hai. Computer ko yeh samjhane ke liye hum Data Types ka use karte hain.
Data Type yeh tay karta hai ki kisi variable mein kis tarah ki value store ki gayi hai aur us variable par aap kaun-kaun se kaam (operations) kar sakte hain. Jaise aap numbers ko aapas mein jod (+) sakte hain, lekin do naamon ko aapas mein multiply (*) nahi kar sakte.
(Integer Box)
-5
45
(String Box)
'Delhi'
'Python'
(Float Box)
99.9
-0.5
जब आप Python में कोई Variable बनाते हैं, तो कंप्यूटर की Memory (RAM) के अंदर ऊपर दिखाए गए
डायग्राम की तरह अलग-अलग कैपेसिटी वाले डिब्बे (Containers) बन जाते हैं:
int (Integer Box): इसमें सिर्फ बिना पॉइंट वाले पूरे
नंबर्स (जैसे 10, -5) ही आ सकते हैं। इसमें आप 'Rahul' जैसा टेक्स्ट नहीं
ठूस सकते।
str (String Box): यह सिर्फ शब्दों (Text) के लिए बना है।
Python की पहचान यह है कि इस डिब्बे में जाने वाली हर चीज़ सिंगल या डबल कोट्स (' ' या
" ") के अंदर बंद होती है।
float (Float Box): यह तिजोरी सिर्फ डेसिमल (पॉइंट वाले)
नंबर्स जैसे 3.14 या 99.9 को संभालने के लिए डिजाइन की गई है।
💡 शॉर्टकट बात: डेटा टाइप कुछ और नहीं, बल्कि कंप्यूटर को यह बताने का तरीका है कि "भाई,
यह वाला डेटा इस टाइप के डिब्बे में डालो और इसपर सिर्फ यही वाले ऑपरेशन्स (जैसे प्लस या माइनस)
करने की इजाजत देना!"
Dynamic Typing in Python
C++ ya Java jaisi purani languages mein variable banane se pehle batana padta tha ki usme kya
store hoga (jaise: int age = 25;).
Lekin Python ek Dynamically Typed language hai. Iska matlab aapko variable ka type pehle
se likhne ki zaroorat nahi hai.
Python ka system itna smart hai ki aap variable mein jo bhi value dalenge, wo apne aap uska type samajh jayega. Niche diye gaye code editor mein dekhiye kaise Python apne aap alag-alag data ko pehchanta hai:
# Python automatically detects the data type
age = 25 # Python ise automatically Integer (int) maan lega
name = "Rahul" # Python ise automatically String (str) maan lega
weight = 65.5 # Python ise automatically Float (float) maan lega
print(age)
print(name)
print(weight)
25 Rahul 65.5
Data Types Kyun Zaroori Hain? (TypeError Example)
Agar data types na hon toh program mein galat calculations ho sakti hain. Jaise agar aap ek text (String) ko kisi number (Integer) ke sath seedhe jodne ki koshish karenge, toh Python safety ke liye ek error show kar dega jise TypeError kehte hain. Isse aapka software crash hone se bach jata hai.
price = 500 # Yeh ek Number hai
tax = "50" # Quotes ke andar hone se yeh Text (String) hai
# Yeh line error degi kyunki number aur text direct nahi jud sakte
total = price + tax
print(total)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Advantages of Data Types (डेटा टाइप्स के फायदे)
Aap soch rahe honge ki jab Python apne aap sab samajh leta hai, toh hume Data Types ke baare mein itna padhne ki kya zaroorat hai? Ek programmer ke liye Data Types ko samajhna isliye zaroori hai kyunki iske niriikhit bade fayde hain:
1. Code Security (सुरक्षा): Yeh galat data operations ko rokta hai. Agar aap
galti se kisi user ki age wale number mein uska naam jodne lagenge, toh Python ka compiler ya
interpreter use wahi rok dega. Isse data corruption nahi hota.
2. Memory Optimization (मेमोरी का सही इस्तेमाल): Computer ki memory (RAM) mein
har data type alag jagah leta hai. Ek text ko store karne mein zyada space lagta hai jabki ek
chhote number ko kam. Data types ki wajah se computer system sahi se memory allocate kar pata
hai.
3. Better Performance & Speed (बेहतर स्पीड): Jab computer ko pehle se pata hota
hai ki samne wala data ek integer (number) hai, toh wo uspar calculations bohot tezi se karta
hai. Agar use har baar data ko check karna pade, toh aapka program slow ho jayega.
4. Readability and Debugging (कोड को समझना आसान): Sahi data types ka use karne
se code saaf dikhta hai aur jab code mein koi galti (bug) aati hai, toh error message padh kar
turant samajh aa jata hai ki problem kahan par hai.
How Python Handles Data Types in Memory
Python mein har data type ek Object ki tarah treat hota hai. Jab aap likhte hain
x = 10, toh Python memory mein 10 naam ka ek object banata hai aur x
ko uska ek pointer (address label) bana deta hai.
Chaliye ek live code example se dekhte hain ki agar hum kisi data type par galat operation karein, toh kya hota hai:
price = 500 # Yeh ek Number hai
tax = "50" # Quotes ke andar hone se yeh Text (String) hai
# Yeh line error degi kyunki number aur text direct nahi jud sakte
total = price + tax
print(total)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python ke Main Data Types
Python की सबसे बड़ी खूबी यह है कि इसमें अलग-अलग तरह के डेटा को संभालने के लिए पहले से ही बेहद ताकतवर डेटा स्ट्रक्चर्स और डेटा टाइप्स बने हुए हैं। किसी भी प्रोजेक्ट को बनाते समय हमें सिर्फ नंबर्स से काम नहीं चलता; हमें यूज़र की लिस्ट बनानी पड़ती है, उनकी यूनिक आईडी (ID) स्टोर करनी पड़ती है और की-वैल्यू (Key-Value) का जोड़ा भी संभालना पड़ता है।
इन सभी को आसानी से समझने के लिए Python ने अपने डेटा टाइप्स को अलग-अलग कैटेगरीज (जैसे Sequence, Mapping, Boolean) में बांटा है। नीचे दिए गए चार्ट (Diagram) में आप Python के पूरे डेटा टाइप परिवार का एक कम्पलीट ओवरव्यू देख सकते हैं, जिससे आपको याद रखने में आसानी होगी:
💡 ऊपर दिए गए चार्ट को कैसे समझें? जैसा कि आपने इमेज में देखा, Python के इन सभी डेटा टाइप्स को हम मुख्य रूप से दो हिस्सों में पढ़ते हैं—साधारण डेटा टाइप्स (जैसे Numbers और Booleans) जो सिर्फ सिंगल वैल्यू स्टोर करते हैं, और कलेक्शन डेटा टाइप्स (जैसे String, Set, Dictionary) जो एक साथ बहुत सारे डेटा को अपने अंदर समेट कर रख सकते हैं।
चलिए अब बिना देर किए इस चार्ट के सबसे पहले और सबसे जरूरी हिस्से—Python Numeric Data Type को गहराई से कोड के साथ समझना शुरू करते हैं!
What are Numeric Data Types ?
Numeric Data Types are the first basic and easy to understand data type of Python . जब bhi hum
programming mein kisi bhi tarah ke numbers ke sath kaam karte hain—chahe wo kisi product ki
price ho, temperature ho, bank account ka balance ho, ya koi bada scientific calculation ho—toh
Python wahan par Numeric Data Type ka istemal karta hai.
Python mein numbers ko unke naye roop aur kaam ke mutabik teen alag-alag bhaagon (sub-types)
mein baanta gaya hai:
1. Integer
Integer ka matlab hota hai bina point wali poore numbers (whole numbers). Yeh positive (plus wale), negative (minus wale) ya zero ho sakte hain. Python mein iski koi fix limit nahi hoti, aap jitna chahein utna bada number isme store kar sakte hain jab tak aapke computer ki memory (RAM) full na ho jaye. Below is the code to store a Integer value in a variable.
user_age = 24
bank_debts = -1500
total_items = 0
print(user_age)
print(bank_debts)
24 -1500
2. Float
Float ka matlab hota hai point wale numbers (decimal numbers). Agar kisi number mein ek single point (.) bhi lag jaye, toh Python use integer nahi balki float maanta hai. Integer ki tarah float bhi positive ya negative dono ho sakte hain.
Ek aur zaroori baat: Float numbers ko likhne ke liye Python scientific notation (e ya E) ka bhi
support karta hai, jiska matlab hota hai "10 ki power". Jaise 3.2e3 ka matlab hai 3.2 * 10^3
(yaani 3200.0).
1. Kisi product ki exact price store karne ke liye (jaise: 99.99) , 2. Percentage nikalne ke
liye (jaise: 85.5%) , 3. GPS coordinates ya weight store karne ke liye (jaise: 65.45 kg) etc.
kaam karne ke liye float data type kaa upyog kiya jaata hai.
Below is the code to store Float value in some variables.
# Float variables ke examples
product_price = 499.50
pi_value = 3.14159
scientific_num = 2.5e3 # Iska matlab hai 2500.0
print(product_price)
print(scientific_num)
499.5 2500.0
3. Complex Numbers
Complex numbers ka istemal aam programming mein bohot kam hota hai, lekin high-level mathematics, physics simulations, electrical engineering aur data science mein yeh bohot zaroori hain.
Ek complex number ke do bhaag hote hain: Real part aur Imaginary part. Python mein imaginary part ko darshane ke liye hum maths ke 'i' ki jagah 'j' या 'J' ka istemal karte hain. Jaise: 2 + 3j (yahan 2 real number hai aur 3j imaginary).
# Complex variables ke examples
num1 = 3 + 4j
num2 = 5j # Agar real part nahi likhenge toh wo 0 mana jayega
print(num1)
print(num1.real) # Sirf real part dekhne ke liye
print(num1.imag) # Sirf imaginary part dekhne ke liye
(3+4j) 3.0 4.0
Useful Built-in Functions for Numbers
Python mein numbers (integers aur floats) ke sath kaam karte waqt hume aksar unhe round-off karne, unki absolute (positive) value nikalne, ya kisi list mein se sabse bada/chhota number dhoodhne ki zaroorat padti hai.
Iske liye Python mein kuch Built-in Functions (pehle se bane banaye functions) milte hain, jinke liye aapko koi alag se library ya module import nahi karna padta. Niche in sabhi zaroori functions ko detail mein samjhaya gaya hai:
1. abs() — Absolute Value
abs() function ka kaam hota hai kisi bhi number ki absolute value batana. Iska matlab yeh hai ki agar aap isme koi negative (minus wala) number dalenge, toh yeh use positive (plus wale) number mein badal dega. Agar number pehle se positive hai, toh wo vaisa hi rahega.
Jab aapko sirf do cheezon ke beech ka antar (difference) nikalna ho aur aap nahi chahte ki answer minus mein aaye (jaise distance ya age ka difference). aisi jagaho per abs() function kaa upyog kiya jaa sakta hai . niche abs() function kaa ek python code diya gaya hai.
distance_1 = -45
distance_2 = 120
print(abs(distance_1))
print(abs(distance_2))
45 120
2. round() — Rounding Off
round() function kisi bhi decimal (float) number ko uske sabse paas wale poore number (integer) mein badal deta hai.
Rule 1 : Agar point ke baad ka number .5 se chhota hai (jaise .4, .3), toh yeh
niche wale number par round-off karega.
Rule 2 : Agar point ke baad ka number .5 ya usse bada hai (jaise .5, .7), toh
yeh upar wale number par round-off karega.
Aap isme yeh bhi bata sakte hain ki aapko point ke baad kitne digits tak ka number chahiye (iske
liye second argument diya jata hai). niche round() — Rounding Off Function kaa ek python code
diya gaya hai.
num1 = 4.3
num2 = 4.7
num3 = 5.5
# Point ke baad kitne digit chahiye uske liye example:
pi_value = 3.14159265
print(round(num1))
print(round(num2))
print(round(num3))
print(round(pi_value, 2)) # Point ke baad sirf 2 digits rakhega
4 5 6 3.14
3. sum() Total Sum
sum() function ka istemal kisi list ya tuple ke andar diye gaye sabhi numbers ka kul jod (total sum) nikalne ke liye kiya jata hai. Iske andar aapko numbers ka ek group bhejna padta hai. niche sum() function kaa ek python code diya gaya hai .
monthly_expenses = [200, 500, 150, 1200]
total_spend = sum(monthly_expenses)
print(total_spend)
2050
Numeric Data Type ke sath Arithmetic Operations
Kyunki yeh saare numbers hain, isliye aap inpar maths ke saare basic operations asaani se chala sakte hain. Python alag-alag numeric types ko aukas ke mutabik khud hi convert (Implicit Typecasting) kar leta hai. Udaharan ke liye, agar aap ek integer aur ek float ko jodenge, toh result hamesha float aayega.
# Alag-alag numbers par math operations
a = 10 # int
b = 3.5 # float
addition = a + b # Jod
subtraction = a - b # Ghatana
multiplication = a * b # Guna
division = a / b # Bhag (Division ka result hamesha float aata hai)
print(addition)
print(division)
13.5 2.857142857142857
Advantages Of Numeric Data Types
1. Unlimited Integer Precision : Python mein integer numbers store karne ki koi
fix limit nahi hoti hai.Aap memory ke anusar jitna chahein utna bada number store kar sakte
hain.
2. Underline for Readability : Bade numbers ko aasaani se padhne ke liye aap
beech mein underscore (_) laga sakte hain.Python ka interpreter in underscores ko calculation
karte waqt apne aap ignore kar deta hai.
3. Automatic Float Division : Jab aap do integers ko normal division (/)
operator se bhag karte hain toh result hamesha float aata hai.Jaise 10 / 2 ka output hamesha
integer 5 ke bajay decimal 5.0 aayega.
4. Immutable Nature : Python ke saare numeric data types poori tarah se
immutable hote hain.Iska matlab hai ki ek baar memory mein number banne ke baad use badla nahi
ja sakta.
5. Multiple Number Systems Support : Python mein aap normal numbers ke alawa
Binary, Octal, aur Hexadecimal numbers bhi likh sakte hain.Iske liye aapko number ke aage 0b,
0o, ya 0x jaise prefixes lagane padte hain.
What are Boolean Data Types ?
Boolean data type ka istemal tab kiya jata hai jab kisi condition ka jawab sirf haan ya naa mein chahiye ho. Python mein boolean data type ke paas sirf do hi values hoti hain:True (सत्य / हाँ)False (असत्य / ना)Note: Python ek case-sensitive language hai, isliye True aur False likhte waqt 'T' aur 'F' ka capital hona zaroori hai. Agar aap lowercase mein true ya false likhenge, toh error aayega. niche boolean data type kaa ek python code diya gaya hai.
a = 5
b = 8
print(a < b)
True
a = 5 : a is a variable in which the value 5 is stored.
b = 8 : b is a variable in which the value 8 is stored.
print(a < b) : This print() function shows the result whether a is less than b or not.
bool() Function aur Truthy vs Falsy Values
Python mein har ek value (chahe wo number ho ya string) internal-level par ya toh True hoti hai ya False. Isko check karne ke liye bool() function ka use kiya jata hai.
1. Falsy Values
Python mein kuch values ko pehle se hi "kuch nahi" ya "khali" maana gaya hai. Isliye jab aap
inpar bool() function lagate hain, toh Python saaf bol deta hai ki yeh False hain.Pure Python
mein sirf yeh kuch hi values Falsy hoti hain:
1. 0 aur 0.0 (Zero number yani kuch nahi value)
2. "" (Khali string, jiske andar koi naam ya akshar na likha ho)
3. [] ya {} (Khali list ya khali dictionary)
4. None (Python mein iska matlab hota hai khali/void)
2. Truthy Values
Falsy values ko chhodkar, duniya ki saari bachi hui values Truthy (True) hoti hain. Agar kisi
variable mein thoda sa bhi data hai, toh Python use sach (True) maanta hai.
1. Koi bhi number (jaise 1, 5, -10 — zero ko chhodkar sab True hain)
2. Bhari hui string (jaise "A", "Rahul", yahan tak ki agar aapne quotes ke andar ek space " "
bhi de diya, toh wo khali nahi hai, isliye True hai)
Real-World Example se Samjhein:
Sochein aap ek website bana rahe hain jahan user ko apna "Phone Number" dalna hai:
1. Agar user ne apna number type kiya (jaise 98765...), toh wo data Truthy hai. Python kahega:
"Haan, data mil gaya (True)!"
2. Agar user ne bina kuch type kiye submit daba diya, toh variable Khali ("") reh jayega, jo ki
Falsy hai. Python kahega: "Bhai, yeh toh khali hai (False), dobara fill karo!"
# Ek bhari hui string aur ek khali string
naam = "Amit"
khali_jagah = ""
# bool() function check karke batayega ki andar ka data True hai ya False
print(bool(naam)) # Output aayega: True (kyunki isme 'Amit' likha hai)
print(bool(khali_jagah)) # Output aayega: False (kyunki yeh ekdum khali hai)
# Numbers ke sath check karein
print(bool(5)) # Output aayega: True (kyunki 5 ek asli value hai)
print(bool(0)) # Output aayega: False (kyunki 0 ka matlab kuch nahi)
True False True False
bool() ek machine hai, usme agar aap koi bhari hui cheez dalenge toh answer True aayega, aur agar koi khali ya zero cheez dalenge toh answer False aayega.
Features of Boolean Data Type
1. Subtype of Integers : Python mein Boolean data type internal roop se Integer
ka hi ek hissa hota hai.Yahan True ka matlab mathematically 1 aur False ka matlab 0 hota hai.
2. Boolean Math Support : Aap Boolean values ko aapas mein jod (+) ya ghataye
(-) bhi sakte hain.Jaise True + True karne par output integer 2 aayega.
3. Fixed Keywords : True aur False Python ke pehle se reserved keywords
hain.Aap inka naam badal kar kisi variable ke roop mein use nahi kar sakte hain.
4. What is a string ?
String is an Immutable data type. This means that changes cannot be made to the created string. String data type is used to store text. String can be created within single quotes, double quotes or triple quotes. Operations like indexing, slicing etc. can be performed with String. NOTE: => If you want to store text in a variable, then there is only one data type to store text. The data type is named String. The code to create a string is given below.
st = "Hello"
print(type(st))
< class 'str' >
st = "Hello" : st is a variable in which String data type is used to store text data and
String is
written in single quotes.
print(type(st)) : type function is used to find out the type of the value stored in st
variable.
1. string indexing
String indexing is a method used to find the text at a specific index number in a string. An example of string indexing is given below.
st = "Hello"
print(st[1])
H
st = "Hello" : A variable named st is created in which the value "Hello" is stored.
print(st[1]) : This print() function prints the element stored at index 1 of the st
variable.
2. String Slicing
String slicing is an important method of string slicing which is used to find the value stored in a string from a starting index number to an ending index number. For example:-
st = "Hello"
print(st[1 : 4])
it
st = "Hello" : A variable named st is created in which the value "Hello" is stored.
print(st[1 : 4]) : This print() function prints the elements stored at index 1 to index 4
of the st
variable.
3. String Concatenation
Joining one or more strings together is called String Concatenation (Method). The string concatenation method is often used when developing large programs. Below is a code for string concatenation.
st = "Hello "
name = "user"
print(st + name)
Hello user
st = "Hello " : A variable named st has been created, in which the value "Hello" has been
stored.
name = "user" : A variable named name st has been created, in which the value "user" has
been
stored. print(st + name) => This print() function adds the st variable and the name variable
together.
Features of String Data Type
1. Immutable Nature : Python mein strings poori tarah se immutable hoti
hain.Aap kisi bani hui string ke kisi ek akshar ko beech mein se badal nahi sakte hain.
2. Rich Built-in Methods : Strings ko handle karne ke liye pehle se bohot saare
functions milte hain.Jaise text ko bada karne ke liye .upper() aur chhota karne ke liye .lower()
use hota hai.
3. Unicode Support : Python 3 mein saari strings default roop se Unicode
standard follow karti hain.Iska matlab aap string mein English ke alawa Hindi, Marathi, ya
Emojis (😀) bhi store kar sakte hain.
3. What is Set Data Type ?
If a programmer wants to keep his data secure, then Set is a very important and interesting data
type in
terms of keeping the data secure. Set is a mutable data type and despite being mutable, no
duplicate
data/value can be stored in a set. Python mein set banane ke liye hum curly brackets {...} ka
istemal karte hain aur items ke beech mein comma , lagate hain.
Note: Agar aapko ek khali (empty) set banana hai, toh aap {} nahi likh sakte, kyunki use Python
dictionary maan leta hai. Khali set hamesha set() function se banta hai.
1. Set Banane ka Tarika aur Uniqueness
Set apne aap duplicate values ko delete kar deta hai. Agar aap ek set mein ek hi number 3 baar bhi likhenge, toh wo use sirf ek hi baar store karega.
# Set banana (Isme duplicate numbers diye hain)
my_set = {1, 2, 2, 3, 4, 4, 4, 5}
print(my_set)
# Empty set banane ka sahi tarika
empty_set = set()
print(type(empty_set))
{1, 2, 3, 4, 5}
< class 'set' >
2. Set Unordered hota hai (No Indexing & Slicing)
Kyunki set ke andar items ka koi fixed order nahi hota, isliye aap isme Indexing ya Slicing ka use nahi kar sakte. Agar aap my_set[0] likhenge, toh error aayega kyunki set mein pehla ya aakhiri jaisa koi concept nahi hota.
names_set = {"Amit", "Rahul", "Karan"}
# Har baar run karne par sequence badal sakta hai
print(names_set)
{'Karan', 'Amit', 'Rahul'}
Set Methods
Set Methods Python mein pehle se bane-banaye (built-in) functions hote hain, jinka istemal set ke andar naye elements ko jodne, purane elements ko hatane, ya do sets ke beech math operations (jaise milaana ya tulna karna) ke liye kiya jata hai.
1. Union Method
Union method is used when one or more sets are combined to form a single set, i.e. if there are more than one common values in the sets, only one value is retained and the rest are removed. In the code editor given below, two sets have been created and only one common value from both the sets has been printed.
A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B))
{1, 2, 3, 4, 5}
A = {1, 2, 3} : A variable named A is created in which the set data is stored.
B = {3, 4, 5} : A variable named B is created in which the set data is stored.
print(A.union(B)) : This print() function displays the common data from both the
variables A and B.
2. Difference Method
Comparison can be done between one or more sets using the Difference Method, that is, the Difference Method is used to find out the values which are not common in all the sets. Two sets have been created in the code editor given below and the values which are not common in both have been printed.
A = {1, 2, 3}
B = {3, 4, 5}
print(A.difference(B))
{1, 2}
A = {1, 2, 3} : A variable named A is created in which the set data is stored.
B = {3, 4, 5} : A variable named B is created in which the set data is stored.
print(A.difference(B)) : This print() function prints those values which are not
present in both
the variables.
3. Subset Method
Subset is a method of Python language, which is used to find out whether all the values of a set are present in another set or not. The output obtained by using the Subset method is True or False. Two sets have been created in the code editor given below and it has been found out whether the values of set B are present in set A or not.
A = {1, 2}
B = {1, 2, 3, 4}
print(A.issubset(B))
True
A = {1, 2} : The set data is stored in the A variable.
B = {1, 2, 3, 4} : There is a variable named B in which some numbers are stored.
print(A.issubset(B)) : This Print() function shows True in the output when all the
numbers stored
in the A variable are found in the B variable .
Features of Set Data Type
1. No Duplicates Allowed : Set apne andar kabhi bhi ek jaisi do values ko store
nahi karta hai.Yeh feature data mein se duplicates hatane ke liye sabse best maana jata hai.
2. Mutable but Elements are Immutable : Aap poore set mein naye items add ya
remove kar sakte hain (Set mutable hai).Lekin set ke andar jo item rakha hai, use aap badal nahi
sakte hain.
3. High Performance Search : Set ke andar kisi item ko dhoodhna (using 'in'
operator) bohot tez hota hai.Yeh list ke muqable hazaron guna tezi se elements ko check kar leta
hai.
5. What is Dictionary Data Type ?
Dictionary is an important concept of Python language, because dictionary is used to keep the data secure. Dictionary is a mutable data type, in which data is stored in the pair of key and value, that is, the created keys definitely have some value. Dictionary in Python language is written in curly brackets {}. In the code editor given below, student data has been stored in a variable using dictionary.
st = {
"Roll Number" : "1",
"Name" : "Shubham",
"Class" : "10th"
}
print(st)
{'Roll Number': '1', 'Name': 'Shubham', 'Class': '10th'}
st = { : A variable named st is created, in which the information of a student is stored
in the
dictionary.
print(st) : This print() function displays the information of the student stored in the
st
variable.
Dictionary Methods
Simply creating a dictionary, or storing data in it, is not enough. You must also know how to access and delete the dictionary. You must also know how to perform operations on the dictionary, such as delete, clear, add, update, etc. The most commonly used dictionary methods are described below.
1. Accessing Value (Method)
Once we create a dictionary, we need to access the dictionary keys. Accessing values from keys is very simple in Python. To access values from keys, functions like indexing or get() are used in Python. The values of a dictionary are accessed from keys in the code editor given below.
employee = {
"id" : "124"
}
print(employee["id"])
124
employee = { : A variable named employee is created, in which the data related to an
employee is
stored in the dictionary.
print(employee["id"]) : This print() function prints the value of the id key of the
employee table
on the screen.
2. Changing the value (Method)
Dictionary is an interesting concept of Python language, hence it does not happen that once the data is stored in the dictionary, changes cannot be made to the stored data. In Python language, the update method is used to change the values of the dictionary. In the code editor given below, information of a car has been stored in a dictionary and changes have been made to the price of the car using the update method.
car = {
"output": "10000"
}
car["prise"] = 20000
print(car)
20000
car = { : A variable named car has been created, in which the information of the car has
been
stored.
car["prise"] = 20000 : The price value of car has been set to "20000".
print(car) : This print() function displays the car variable.
3. Adding a new Key-Value (Method)
Dictionary is a mutable data type, so once the key and value are stored in the dictionary, new keys and values can be added later if needed. Update method is used to add new key and value to the dictionary. The name of car has been added to the dictionary given below.
\car = {
"output": "10000"
}
car["Name"] = "sssss"
print(car)
{'prise': '10000', 'Name': 'sssss'}
car = { : A variable named car has been created, in which the information of car has been
stored in
the dictionary.
car["Name"] = "sssss" : New key values named "Name" and "sssss" have been added to the
dictionary
stored in the car variable.
print(car) : This print() function displays the car variable.
4. Deleting the Dictionary (Method)
"del" is already a reserved keyword in Python language, which is used to delete any value or element. In Python language, 'Del' keyword is used to delete a dictionary or the key values of a dictionary. Below, the key value of a dictionary has been deleted.
Student = {
"Roll Number" : "10"
}
del Student["Roll Number"]
print(Roll Number)
{'prise': '10000', 'Name': 'sssss'}
Student = { : A variable named Student is created, in which the information of a student
from the
dictionary is stored.
del Student["Roll Number"] : The "Roll Number" key and value of the Student dictionary
are deleted.
print(Student) : This print() function displays the Student variable.
Features of Dictionary Data Type
1. Key-Value Mapping : Yeh data ko anukram (index) ke bajay arthpurna naamon
(keys) se pehchanne ka tarika deti hai.Isse code ko padhna aur samajhna bohot aasan ho jata hai.
2. Ordered by Insertion (Python 3.7+) : Python 3.7 ke baad se dictionaries
elements ke jodne ke kram (order) ko yaad rakhti hain.Aap jis kram mein data dalenge, wo usi
kram mein hamesha print hogga.
3. Dynamic and Nestable : Dictionary ke andar aap kisi bhi tarah ka data (jaise
list ya dusri dictionary) store kar sakte hain.Ise Nested Dictionary kehte hain, jo complex data
handle karne ke kaam aati hai.
Mutable vs Immutable Data Types
Python mein jab hum koi variable banate hain, toh wo memory (RAM) mein ek object ke roop mein
store hota hai. Python ke saare data types ko is baat par do bhaagon mein baanta gaya hai ki kya
hum unki value ko banne ke baad badal (modify) sakte hain ya nahi.
Mutable Data Types : Jinhe memory mein usi jagah (in-place) badla ja sake.
Immutable Data Types : Jinhe memory mein banne ke baad kabhi badla na ja sake.
1. Immutable Data Types
Immutable ka matlab hota hai jo badla na ja sake. Ek baar jab aap memory mein koi immutable object bana dete hain, toh uske andar ka data freeze ho jata hai.
Agar aap us variable ki value ko badalna chahenge, toh Python purani value ko nahi badlega. Wo memory mein ek ekdum naya object banayega aur aapke variable ko us naye address par bhej dega. Numbers (int, float, complex) , Strings , Booleans , Tuples aadi immutable data types hote hai
# ==========================================
# EXAMPLES OF IMMUTABLE DATA TYPES IN PYTHON
# ==========================================
# 1. Integer (int)
age = 25
print("1. Integer Type:", type(age), "Value:", age)
# 2. Float (float)
price = 99.99
print("2. Float Type:", type(price), "Value:", price)
# 3. String (str)
name = "Rahul"
print("3. String Type:", type(name), "Value:", name)
# 4. Boolean (bool)
is_coding = True
print("4. Boolean Type:", type(is_coding), "Value:", is_coding)
# 5. Tuple (tuple)
coordinates = (10.5, 20.8)
print("5. Tuple Type:", type(coordinates), "Value:", coordinates)
# -----------------------------------------------------------
# PROOF OF IMMUTABILITY (Inme se kisi ko badla nahi ja sakta)
# -----------------------------------------------------------
print("\n--- Try to modify an Immutable object ---")
# Try to modify String character
try:
name[0] = "K" # Error: Cannot change 'R' to 'K'
except TypeError as error:
print("String Error:", error)
# Try to modify Tuple item
try:
coordinates[0] = 50.5 # Error: Cannot change items in a tuple
except TypeError as error:
print("Tuple Error:", error)
1. Integer Type:Value: 25 2. Float Type: < class 'float' > Value: 99.99 3. String Type: < class 'str' > Value: Rahul 4. Boolean Type: < class 'bool' > Value: True 5. Tuple Type: < class 'tuple' > Value: (10.5, 20.8) --- Try to modify an Immutable object --- String Error: 'str' object does not support item assignment Tuple Error: 'tuple' object does not support item assignment
2. Mutable Data Types
Mutable ka matlab hota hai jise badla ja sake. In data types ke sath yeh sahuliyat hoti hai ki aap memory mein unka address badle bina, unke andar ki values ko jab chahein tab naya roop de sakte hain, jod sakte hain ya delete kar sakte hain. Lists , Dictionaries , Sets aadi immutable data types hote hai
# ==========================================
# EXAMPLES OF MUTABLE DATA TYPES IN PYTHON
# ==========================================
# 1. List (list)
numbers_list = [10, 20, 30]
print("1. Original List:", numbers_list)
# Modification: List ke item ko directly badal sakte hain
numbers_list[1] = 99
print(" Modified List:", numbers_list)
# 2. Dictionary (dict)
user_dict = {"name": "Amit", "age": 25}
print("\n2. Original Dictionary:", user_dict)
# Modification: Age ko badalna aur city ko naya jodna
user_dict["age"] = 26
user_dict["city"] = "Delhi"
print(" Modified Dictionary:", user_dict)
# 3. Set (set)
my_set = {1, 2, 3}
print("\n3. Original Set:", my_set)
# Modification: Set mein naya item add karna aur remove karna
my_set.add(5)
my_set.discard(2)
print(" Modified Set:", my_set)
1. Original List: [10, 20, 30]
Modified List: [10, 99, 30]
2. Original Dictionary: {'name': 'Amit', 'age': 25}
Modified Dictionary: {'name': 'Amit', 'age': 26, 'city': 'Delhi'}
3. Original Set: {1, 2, 3}
Modified Set: {1, 3, 5}
| Feature | Mutable Data Types | Immutable Data Types |
|---|---|---|
| Meaning | These data types can be changed or modified in-place after they are created. | These data types cannot be changed or modified once they are created. |
| Memory Behavior | Modifying the data does not create a new object; the memory address (ID) stays the same. | Modifying the data automatically creates a new object in memory, changing the address (ID). |
| Examples | List (list), Dictionary (dict), Set (set)
|
Integer (int), Float (float), String (str),
Tuple (tuple), Boolean (bool) |
| Speed & Performance | Since their size can change dynamically, their processing speed is slightly slower. | Since their size is fixed, they are highly optimized and access speed is very fast. |
| Dict Key Support | They cannot be used as a Key inside a Python Dictionary because their value can change. | They are perfect for use as a Dictionary Key because their value remains constant. |
Features of Mutable vs Immutable
1. Memory Efficiency : Immutable types (jaise strings) memory bachaate hain
kyunki ek hi value ko kai variables share kar sakte hain.Is feature ko Python mein 'Object
Interning' kaha jata hai.
2. Thread Safety : Immutable data types multi-threaded programming mein poori
tarah se safe hote hain.Inhe ek sath kai programs bina data corrupt kiye padh sakte hain.
3. Flexibility of Mutable : Mutable types badalte hue data (jaise shopping cart
items) ko handle karne ke liye best hain.Isme baar-baar naya object na banne se memory par faltu
ka load nahi padta.
Type Casting (Implicit vs Explicit)
Python mein Type Casting (jise Type Conversion bhi kaha jata hai) ka matlab hota hai ek data type ke value ko dusre data type mein badalna. Jaise kisi number ko text (string) mein badalna ya kisi decimal number (float) ko normal number (integer) mein badalna. Python mein type casting do tarah ki hoti hai:
1. Implicit Type Conversion (Automatic Conversion)
Implicit type conversion tab hota hai jab Python bina aapke kahe, apne aap ek data type ko dusre data type mein badal deta hai.
Python yeh kaam tabhi karta hai jab data ka nuksan (data loss) na ho raha ho. Python hamesha "chote" data type ko "bade" data type mein convert karta hai taaki accuracy bani rahe. niche Implicit का ek python code diya gaya hai .
# Integer value
num_int = 12
# Float value
num_flo = 10.5
# Dono ko add kiya
result = num_int + num_flo
print("Result:", result)
print("Result ka Data Type:", type(result))
Result: 22.5 Result ka Data Type: < class 'float' >
Upar ke example mein num_int ek integer tha. Lekin plus (+) karne ke baad jo result aaya, woh 22.5 (float) ban gaya. Python ne aisa isliye kiya kyunki agar woh result ko integer banata, toh .5 gayab ho jata, jisse aapka calculation galat ho jata. Is automatic process ko hi Implicit Conversion kehte hain.
2. Explicit Type Casting (Forced Conversion)
Explicit Type Casting tab hoti hai jab hum (developer) khud Python ko bolte hain ki "Is data type ko badal kar us data type mein convert karo." Iske liye hum Python ke inbuilt functions (jaise int(), float(), str()) ka istemal karte hain.
Iski zaroorat tab padti hai jab Python automatic conversion nahi kar pata. Jaise agar aap kisi text "10" ko number 5 ke sath jodna chahein, toh Python error de dega. Wahan aapko explicit casting karni padegi.Python mein explicit casting ke liye mukhyatah yeh functions use hote hain:
A. int() Function
Yeh kisi bhi float value ya valid numeric string ko integer mein badalta hai. Dhayan rahe, float ko int mein badalte waqt decimal ke baad ka hissa hat jata hai (round off nahi hota, sirf kat jata hai).
# Float ko int mein badalna
a = int(10.99) # Output: 10 (decimal hat gaya)
# String ko int mein badalna
b = int("25") # Output: 25
print(a, type(a))
print(b, type(b))
B. float() Function
Yeh kisi integer ya valid numeric string ko float (decimal number) mein badal deta hai. niche float() function kaa ek python code diya gaya hai.
# Int ko float mein badalna
x = float(5) # Output: 5.0
# String ko float mein badalna
y = float("4.25") # Output: 4.25
print(x, type(x))
print(y, type(y))
C. str() Function
Yeh kisi bhi data type (number, float, list, etc.) ko string (text) mein badal deta hai. Jab aapko numbers ko text ke sath jodna ho, tab yeh bahut kaam aata hai.
age = 25
# Direct print("My age is " + age) likhne par error aayega
# Isliye str() ka use karenge:
message = "My age is " + str(age)
print(message) # Output: My age is 25
D. list(), tuple(), set() Functions
Aap inka use karke collection data types ko bhi aapas mein badal sakte hain.
1. list() Function : Yeh kisi bhi iterable (jaise tuple ya set) ko ek
order-wise editable array ya list mein badal deta hai.
2. tuple() Function: Yeh list ya set ko tuple mein badalta hai, jisse uski
values secure (read-only) ho jati hain aur change nahi ki ja sakteen.
3. set() Function: Yeh data ko unique collection mein badal deta hai, jisse
saari duplicate values apne aap remove ho jati hain.
# 1. List ko Tuple mein badalna
my_list = [1, 2, 2, 3]
my_tuple = tuple(my_list) # Output: (1, 2, 2, 3)
# 2. Tuple ko Set mein badalna (Set duplicate values ko automatic hata deta hai)
my_set = set(my_tuple) # Output: {1, 2, 3}
# 3. Set ko wapas List mein badalna
final_list = list(my_set) # Output: [1, 2, 3]
| Feature | Implicit Type Conversion | Explicit Type Casting |
|---|---|---|
| Performed By | Done automatically by the Python interpreter. | Done manually by the developer using built-in functions. |
| Data Loss | No data loss occurs (Python safely upgrades data types). | Data loss can occur (e.g., losing decimals when casting float to int). |
| Errors | Completely safe; never causes runtime errors or exceptions. | Can cause errors (like ValueError) if the conversion is invalid. |