Python Notes
Python ke sabhi built-in data types — int, float, str, bool, list, tuple, set, dict, None — ko deeply samjhein examples, diagrams aur comparisons ke saath.
Hindi: Data types matlab data ke prakar — jaise ek dukaan mein alag alag cheezein hoti hain (kapde, khaana, electronics), waise hi computer mein alag alag types ka data hota hai. Python mein har value ka ek type hota hai.
2. Numeric Types
Integer (int)
Hindi: Integer matlab poore number — bina decimal ke. Python mein integers ki size unlimited hai!
# Integer examples
age = 25
population = 1_380_004_385 # India's population (underscores for readability)
negative = -42
big_number = 10 ** 100 # googol!
print(type(age))
print(type(big_number))
# Integer in different bases
decimal = 255
binary = 0b11111111 # binary (starts with 0b)
octal = 0o377 # octal (starts with 0o)
hexadecimal = 0xFF # hex (starts with 0x)
print(f"Decimal: {decimal}")
print(f"Binary: {binary}")
print(f"Octal: {octal}")
print(f"Hex: {hexadecimal}")
print(f"All equal: {decimal == binary == octal == hexadecimal}")<class 'int'> <class 'int'> Decimal: 255 Binary: 255 Octal: 255 Hex: 255 All equal: True
Float (float)
Hindi: Float matlab decimal numbers — jaise price, height, percentage mein hote hain.
# Float examples
pi = 3.14159265358979
temperature = -15.5
scientific = 1.5e10 # 1.5 × 10^10 = 15000000000.0
small = 2.5e-3 # 0.0025
print(f"Pi: {pi}")
print(f"Scientific: {scientific}")
print(f"Small: {small}")
print(f"Type: {type(pi)}")
# Float precision issue!
result = 0.1 + 0.2
print(f"0.1 + 0.2 = {result}") # Not exactly 0.3!
print(f"Rounded: {round(result, 1)}") # Use round() for precisionPi: 3.14159265358979 Scientific: 15000000000.0 Small: 0.0025 Type: <class 'float'> 0.1 + 0.2 = 0.30000000000000004 Rounded: 0.3
Complex (complex)
# Complex numbers — used in engineering, signal processing
z1 = 3 + 4j
z2 = complex(2, -3) # another way
print(f"z1 = {z1}")
print(f"z2 = {z2}")
print(f"Real part: {z1.real}")
print(f"Imaginary part: {z1.imag}")
print(f"Magnitude: {abs(z1)}") # √(3² + 4²) = 5.0
print(f"Sum: {z1 + z2}")z1 = (3+4j) z2 = (2-3j) Real part: 3.0 Imaginary part: 4.0 Magnitude: 5.0 Sum: (5+1j)
Boolean (bool)
Hindi: Boolean sirf do values rakhta hai:TrueyaFalse. Yeh int ka subclass hai —True= 1,False= 0.
<class 'bool'> 2 5 1 False True False True False True False
Falsy Values Table
| Value | Type | bool() |
|---|---|---|
0 | int | False |
0.0 | float | False |
"" | str | False |
[] | list | False |
() | tuple | False |
{} | dict | False |
set() | set | False |
None | NoneType | False |
| Everything else | any | True |
3. String (str)
Hindi: String matlab text — characters ka sequence. Python mein strings immutable hain (change nahi ho sakti).
# String creation
name = "Rahul Kumar"
city = 'Mumbai'
multiline = """This is
a multiline
string"""
print(name)
print(city)
print(multiline)
print(type(name))
# String properties
print(f"Length: {len(name)}")
print(f"Upper: {name.upper()}")
print(f"Starts with R: {name.startswith('R')}")Rahul Kumar Mumbai This is a multiline string <class 'str'> Length: 11 Upper: RAHUL KUMAR Starts with R: True
4. List (list)
Hindi: List ek ordered collection hai jisme alag alag types ke items ho sakte hain, aur yeh mutable hai (change ho sakti hai). Yeh Python ka sabse commonly used data type hai.
['apple', 'banana', 'mango', 'orange'] Type: <class 'list'> Length: 4 First: apple Last: orange Slice: ['banana', 'mango'] ['apple', 'cherry', 'mango', 'orange'] Popped: grapes
5. Tuple (tuple)
Hindi: Tuple list ki tarah hi hai lekin immutable hai — ek baar banao, change nahi hoga. Use it for data that shouldn't change (like coordinates, RGB colors, dates).
(28.6139, 77.209) <class 'tuple'> Length: 7 Latitude: 28.6139 Monday: Mon Last day: Sun Lat: 28.6139, Lon: 77.209 Tuples are immutable — cannot modify!
6. Dictionary (dict)
Hindi: Dictionary ek key-value store hai — jaise real dictionary mein word → meaning hoti hai. Python dict mein koi bhi key aur koi bhi value rakh sakte hain.
{'name': 'Priya Sharma', 'roll_no': 2301, 'grade': '10th', 'marks': [...], 'is_active': True}
Type: <class 'dict'>
Name: Priya Sharma
Marks: [85, 92, 78, 96, 88]
Phone: Not available
All key-value pairs:
name: Priya Sharma
roll_no: 2301
grade: 11th
marks: [85, 92, 78, 96, 88]
email: priya@school.com7. Set (set)
Hindi: Set ek unordered collection hai jisme duplicate values nahi hoti. Use it for unique items, membership testing, and set operations (union, intersection).
{'apple', 'banana', 'mango'}
<class 'set'>
Original: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Unique: {1, 2, 3, 4}
Union (|): {1, 2, 3, 4, 5, 6, 7, 8}
Intersection (&): {4, 5}
Difference (a-b): {1, 2, 3}
Symmetric diff (^): {1, 2, 3, 6, 7, 8}
3 in a: True
9 in a: False8. NoneType (None)
Hindi: None Python ka null value hai — matlab "kuch nahi" ya "value nahi hai abhi." Yeh ek special singleton object hai.# None usage
result = None
print(result)
print(type(result))
# Common uses of None
def find_user(user_id):
# Simulate database search
if user_id == 1:
return {"name": "Rahul", "id": 1}
return None # not found
user = find_user(1)
print(f"Found: {user}")
user = find_user(99)
if user is None: # always use 'is None', not '== None'
print("User not found!")
# None as default parameter
def greet(name=None):
if name is None:
name = "Guest"
return f"Hello, {name}!"
print(greet())
print(greet("Anjali"))None
<class 'NoneType'>
Found: {'name': 'Rahul', 'id': 1}
User not found!
Hello, Guest!
Hello, Anjali!9. Mutable vs Immutable Types
IMMUTABLE (cannot change after creation)
┌──────────────────────────────────────────┐
│ int, float, complex, bool │
│ str │
│ tuple │
│ frozenset │
│ bytes │
└──────────────────────────────────────────┘
MUTABLE (can change after creation)
┌──────────────────────────────────────────┐
│ list │
│ dict │
│ set │
│ bytearray │
└──────────────────────────────────────────┘
Same object? False Same object? True
10. Comprehensive Data Type Comparison
| Type | Ordered | Mutable | Duplicates | Syntax | Access |
|---|---|---|---|---|---|
int | N/A | ❌ | N/A | 42 | N/A |
float | N/A | ❌ | N/A | 3.14 | N/A |
str | ✅ | ❌ | ✅ | "hello" | s[0] |
list | ✅ | ✅ | ✅ | [1,2,3] | l[0] |
tuple | ✅ | ❌ | ✅ | (1,2,3) | t[0] |
dict | ✅(3.7+) | ✅ | Keys: ❌ | {k:v} | d[k] |
set | ❌ | ✅ | ❌ | {1,2,3} | N/A |
frozenset | ❌ | ❌ | ❌ | frozenset() | N/A |
bool | N/A | ❌ | N/A | True | N/A |
NoneType | N/A | ❌ | N/A | None | N/A |
11. Type Checking
42 → type: int | isinstance int: True
hello → type: str | isinstance int: False
3.14 → type: float | isinstance int: False
True → type: bool | isinstance int: True
[1, 2] → type: list | isinstance int: False
{'a': 1} → type: dict | isinstance int: False
(1, 2) → type: tuple | isinstance int: False
{3, 4} → type: set | isinstance int: False
None → type: NoneType | isinstance int: FalseHindi:boolkaisinstance(True, int)True aata hai kyunkiboolaslmeinintka subclass hai Python mein!
Real-World Example: E-commerce Product
Product: WoHo Wireless Headphones
Price: ₹2499.99
In Stock: Yes
Colors: Black, White, Blue
Tags: {'electronics', 'audio', 'wireless'}
Discount: None available
Specifications:
brand: WoHo
model: WH-1000
battery_hours: 30
weight_grams: 254Practice Exercises
Exercise 1 — Type Identification
What is the data type of each? Write your answers then verify with type():
Exercise 2 — Choose the Right Type
For each, which data type is best and why?
- Days of the week (fixed, ordered)
- A shopping cart (ordered, modifiable)
- Username → email mapping
- Unique visitor IDs
- Whether user is logged in
Exercise 3 — Set Operations
Given two lists of students:
- Section A: ["Rahul", "Priya", "Amit", "Neha", "Karan"]
- Section B: ["Priya", "Vikram", "Neha", "Sunita", "Karan"]
Find: students in both sections, only in A, only in B, in either section.
Interview Questions
Q1. What is the difference between a list and a tuple in Python? > Both are ordered sequences, but lists are mutable (can be modified) while tuples are immutable. Lists use [], tuples use (). Use tuples for fixed data (coordinates, RGB values), lists for collections that change. Tuples are slightly faster and can be used as dictionary keys.
Q2. When would you use a set instead of a list? > When you need unique elements, fast membership testing (O(1) vs O(n)), or set operations (union, intersection, difference). Sets don't maintain order and don't support indexing.
Q3. What is the difference between == and is for None checking? > Always use is None (not == None). is checks identity (same object in memory). Since None is a singleton, x is None is the correct and faster check. == None can be overridden by __eq__ in custom classes.
Q4. Are booleans a subtype of integers in Python? > Yes! bool is a subclass of int. True == 1 and False == 0. You can do arithmetic with booleans: True + True == 2. isinstance(True, int) returns True.
Q5. What is the difference between a dict and a set (both use {})? How does Python distinguish them? > An empty {} creates a dict, not a set! Use set() for an empty set. For non-empty: {1, 2, 3} is a set (values only), {"a": 1} is a dict (key-value pairs). Python identifies them by the presence of colons (:) in key-value pairs.
⚠️ Common Mistakes
1. Empty {} ko set samajhna ❌
# ❌ Galat — yeh dict hai, set nahi!
empty = {}
print(type(empty)) # <class 'dict'>
# ✅ Sahi — empty set banane ke liye set() use karo
empty_set = set()
print(type(empty_set)) # <class 'set'>2. Single-element tuple mein comma bhoolna ❌
# ❌ Galat — yeh int hai, tuple nahi!
not_a_tuple = (42)
print(type(not_a_tuple)) # <class 'int'>
# ✅ Sahi — trailing comma zaroori hai!
actual_tuple = (42,)
print(type(actual_tuple)) # <class 'tuple'>3. Float comparison == se karna ❌
# ❌ Galat — floating point precision issue!
print(0.1 + 0.2 == 0.3) # False 😱
# ✅ Sahi — round() ya math.isclose() use karo
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True ✅4. == None use karna instead of is None ❌
# ❌ Galat — == override ho sakta hai custom classes mein
if x == None:
pass
# ✅ Sahi — is None use karo (identity check)
if x is None:
pass5. Mutable default arguments use karna ❌
# ❌ Galat — same list share hogi har function call mein!
def add_item(item, items=[]):
items.append(item)
return items
# ✅ Sahi — None use karo as default
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items6. String ko modify karne ki koshish karna ❌
7. List copy karte waqt reference copy karna ❌
✅ Key Takeaways
- 🔢 Python mein har cheez ek object hai — integers, strings, functions sab objects hain with a type
- 📦 Numeric types:
int(unlimited size),float(decimal),complex(engineering),bool(True/False — int ka subclass) - 📝 Strings immutable hain — modify karne pe naya object banta hai, purana change nahi hota
- 📋 List vs Tuple: List mutable hai (
[]), Tuple immutable hai (()). Fixed data ke liye tuple, changeable data ke liye list - 🗂️ Dictionary key-value pairs store karta hai — Python 3.7+ mein insertion order maintain hota hai
- 🎯 Set mein duplicates nahi hote — fast membership testing O(1) aur mathematical set operations ke liye best
- 🚫
Noneka matlab "no value" — always check withis None, never== None - 🔒 Immutable types: int, float, str, tuple, frozenset, bytes — inhe dictionary keys ki tarah use kar sakte ho
- 🔓 Mutable types: list, dict, set, bytearray — in-place modify ho sakte hain, careful with references!
- 🧪 Type checking:
type()exact type batata hai,isinstance()inheritance bhi check karta hai — preferisinstance()
❓ FAQ
Q1. Python mein dynamically typed ka kya matlab hai? > Python mein aapko variable ka type declare nahi karna padta. x = 10 likhne pe Python khud samajh jata hai ki yeh int hai. Same variable ko baad mein x = "hello" bhi assign kar sakte ho — type runtime pe decide hota hai, compile time pe nahi.
Q2. type() aur isinstance() mein kya difference hai? > type(x) exact type batata hai. isinstance(x, int) check karta hai ki x us type ka hai YA uska subclass hai. Example: type(True) returns bool, lekin isinstance(True, int) returns True kyunki bool int ka subclass hai. Best practice: isinstance() use karo.
Q3. Mutable aur immutable mein practically kya farak padta hai? > Immutable objects ko dictionary keys ya set elements ki tarah use kar sakte ho (kyunki inki hash value change nahi hoti). Mutable objects ke saath reference sharing ka issue aata hai — agar ek variable se change karo toh dusre mein bhi reflect hota hai. Function arguments mein bhi mutable defaults se bugs aa sakte hain.
Q4. Kab list use karein aur kab tuple? > List use karo jab data change ho sakta hai — shopping cart items, user inputs, dynamic collections. Tuple use karo jab data fixed ho — coordinates (x, y), RGB colors (255, 0, 0), database records, function se multiple values return karna. Tuples thode faster bhi hote hain aur less memory lete hain.
Q5. Empty set kaise banayein jab {} dict banta hai? > set() constructor use karo. {} hamesha empty dict banata hai Python mein. Non-empty set ke liye {1, 2, 3} likh sakte ho, lekin empty ke liye sirf set() kaam karega. Similarly, frozenset() se empty frozenset banta hai.
Q6. Python mein integer ki maximum size kya hai? > Python 3 mein integers ki koi fixed size nahi hai — yeh arbitrary precision hain! Aap 10 ** 1000 bhi calculate kar sakte ho bina overflow ke. Yeh C/Java se different hai jahan int 32-bit ya 64-bit hota hai. Python internally memory dynamically allocate karta hai.
Q7. None aur 0 ya empty string "" mein kya farak hai? > None ka matlab hai "koi value hi nahi hai" — yeh absence of value represent karta hai. 0 ek valid integer value hai, "" ek valid (empty) string hai. Function jo kuch return nahi karta woh implicitly None return karta hai. Teeno falsy hain (bool() se False dete hain), lekin meaning alag hai.
Q8. Kya hum apne custom data types bana sakte hain? > Haan! Python mein classes use karke apne custom types bana sakte ho. class Student: likhke apna type define karo. Custom classes by default mutable hoti hain. @dataclass decorator use karke quickly structured data types bana sakte ho. Advanced: __hash__ aur __eq__ define karke apni class ko hashable (set/dict key usable) bana sakte ho.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Data Types.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, data, types
Related Python Master Course Topics