🐍 Python List, Tuple और Dictionary – फर्क और Examples [2025 Updated]
Table of Contents
TogglePython में **List**, **Tuple**, और **Dictionary** तीन सबसे ज़्यादा इस्तेमाल होने वाले Data Structures हैं। ये data को store, organize और access करने के अलग-अलग तरीके देते हैं। आइए आसान हिंदी में इनका फर्क और Examples देखें।
Feature | List | Tuple | Dictionary |
---|---|---|---|
Definition | Ordered, Mutable collection | Ordered, Immutable collection | Key-Value pair collection |
Syntax | [1, 2, 3] |
(1, 2, 3) |
{"a": 1, "b": 2} |
Mutability | ✅ Changeable | ❌ Not Changeable | ✅ Changeable |
Use Case | Dynamic data storage | Fixed reference data | Mapping keys to values |
📋 Python में List क्या है?
Python में List एक ordered और mutable data structure है,
जो multiple values को एक variable में store करने की सुविधा देता है।
इसे हम [ ]
square brackets में define करते हैं और values comma से अलग होती हैं।
# Python List Example fruits = ["apple", "banana", "cherry"] print(fruits) # Output: ['apple', 'banana', 'cherry']
✅ Mutable
List के elements बदले, जोड़े या हटाए जा सकते हैं।
📏 Indexed
हर element का एक index होता है जो 0 से शुरू होता है।
📦 Mixed Data
List में string, integer, float, और दूसरी lists भी store हो सकती हैं।
💡 Example: List में नया item जोड़ना
fruits = ["apple", "banana", "cherry"] fruits.append("mango") print(fruits) # Output: ['apple', 'banana', 'cherry', 'mango']
🔗 Python में Tuple क्या है?
Tuple एक ordered, immutable collection है जिसे ( )
में लिखा जाता है।
List की तरह index होता है, पर इसे बदला नहीं जा सकता—इसलिए fixed records या सुरक्षित डेटा के लिए बढ़िया है।
✅ Immutable
बन जाने के बाद items बदले नहीं जाते—accidental change से सुरक्षा।
⚡ Fast & Hashable
अक्सर list से हल्का/तेज़। Hashable होने पर dict
keys के रूप में उपयोग संभव।
🧾 Fixed Records
(lat, lon), (r, g, b), (id, name, price) जैसी स्थायी जोड़ी/रिकॉर्ड के लिए बढ़िया।
🧩 Syntax & Basics
# Tuple बनाना
t = (10, 20, 30)
print(t[0], t[-1]) # 10 30
# Single-element tuple में कॉमा जरूरी
t1 = (5) # यह int है, tuple नहीं
t2 = (5,) # यह tuple है
print(type(t1), type(t2)) # <class 'int'> <class 'tuple'>
# Packing & Unpacking
point = (12.5, 7.0)
x, y = point
print(x, y) # 12.5 7.0
# Extended unpacking
a, *mid, b = (1,2,3,4,5)
print(a, mid, b) # 1 [2,3,4] 5
🛠 Common Operations
t = ("a", "b", "a", "c")
print(len(t)) # 4
print(t.count("a")) # 2
print(t.index("c")) # 3
print(("x","y")+("z",))# ('x','y','z')
print(("ha",)*3) # ('ha','ha','ha')
🔒 Tuple as Dict Key
# Hashable होने पर tuple key बन सकता है
prices = {("apple", "kg"): 180, ("banana", "dozen"): 60}
print(prices[("apple","kg")]) # 180
Note: Tuple के अंदर अगर mutable object (जैसे list) होगा तो वह hashable नहीं रहेगा।
⚠️ Pitfall: Immutability vs Nested Mutables
t = (1, [2,3], 4)
# t[1] = [9] # ❌ TypeError (tuple immutable)
t[1].append(99) # ✅ अंदर वाली list mutable है
print(t) # (1, [2, 3, 99], 4)
💡 कब Tuple चुनें?
- स्थिर/फिक्स्ड रिकॉर्ड (जैसे geo-coordinates, RGB, config triplets)
- Dictionary keys चाहिए और order/size fix है
- Performance/Memory में हल्का स्ट्रक्चर चाहिए
🗂️ Python में Dictionary क्या है? (Key–Value Store)
Dictionary एक unordered, mutable mapping है जो key → value के रूप में डेटा रखता है।
इसे { }
में लिखा जाता है और keys hashable होनी चाहिए (जैसे str
, int
, tuple
).
🔑 Fast Lookup
Key के आधार पर O(1) औसत समय में access/update।
🧰 Mutable & Dynamic
Values कुछ भी हो सकती हैं (list, dict, tuple…)
🚫 Keys must be Hashable
Mutable types (जैसे list) key नहीं बन सकते।
# Create
user = {"id": 1, "name": "A", "skills": ["py","sql"]}
print(user["name"]) # Read (KeyError if missing)
# Safe read with default
print(user.get("email", "N/A"))
# Update / Insert
user["name"] = "Anita"
user["email"] = "a@b.com"
# Delete
del user["id"] # KeyError if missing
removed = user.pop("xyz", None) # safe remove
print(user)
info = {"a":1, "b":2, "c":3}
for k in info: # default = keys
print(k, info[k])
for v in info.values():
print(v)
for k, v in info.items():
print(k, "→", v)
# squares for odd numbers
nums = [1,2,3,4,5]
sq_odd = {n: n*n for n in nums if n % 2}
print(sq_odd) # {1:1, 3:9, 5:25}
profile = {"name":"Ravi", "skills":["py"]}
# get(default)
city = profile.get("city", "Dehradun")
# setdefault: key न हो तो set करके value return
skills = profile.setdefault("skills", [])
skills.append("sql")
# update: merge/overwrite
profile.update({"name":"Ravi Kumar", "city":"Dehradun"})
print(profile)
student = {
"id": 101,
"name": "Meera",
"marks": {"math": 92, "eng": 88}
}
print(student["marks"]["math"]) # 92
cfg = {"db":{"host":"localhost","port":5432}}
host = cfg.get("db", {}).get("host", "127.0.0.1")
print(host)
d.copy()
= shallow; deep के लिए copy.deepcopy
🎯 List vs Tuple vs Dictionary — कब क्या चुनें? (with Practice)
इस सेक्शन में हम python list tuple dictionary in hindi के चुनाव को आसान बनाने के लिए एक decision table, साथ ही 8 practical problems (hint + solution) देखेंगे।
Criteria | List | Tuple | Dictionary |
---|---|---|---|
Mutability | ✅ Mutable | ❌ Immutable | ✅ Mutable (keys immutable होने चाहिए) |
Ordering / Index | Ordered, index-based | Ordered, index-based | Insertion-ordered (Py3.7+), key-based access |
Duplicates Allowed? | Yes | Yes | Keys unique, values duplicate allowed |
Best Use | Dynamic sequences (change/append) | Fixed records (safe, hashable) | Key → Value mapping, fast lookup |
Performance/Memory | Flexible, थोड़ा heavy vs tuple | हल्का/तेज़, hashable | Hash map overhead, lookup O(1) avg |
Examples | [1, 2, 3] , users.append(x) |
(lat, lon) , (r,g,b) |
{"name":"A", "age":20} |
Choose When… | बार-बार बदलाव/insert/delete हों | डेटा स्थिर हो, accidental edit से बचना हो | लेबल/कुंजी से access करना हो |
🧪 8 Practice Problems (Hint + Solution)
P1. Merge Lists → Unique Sorted
दोनो lists merge कर unique ascending list बनाएं।
💡 Hint
set + sorted
✅ Solution
a = [3,1,2,2]; b = [2,5,3]
res = sorted(set(a + b))
print(res) # [1,2,3,5]
P2. Swap Coordinates (Tuple)
(x, y) → (y, x)
💡 Hint
Pythonic unpacking
✅ Solution
pt = (12.5, 7.0)
x, y = pt
pt = (y, x)
print(pt) # (7.0, 12.5)
P3. Word Frequency (Dict)
sentence के हर शब्द का count निकालें।
💡 Hint
split + dict.setdefault / collections.Counter
✅ Solution (basic)
text = "to be or not to be"
freq = {}
for w in text.split():
freq[w] = freq.get(w, 0) + 1
print(freq)
P4. Use Tuple as Dict Key
(item, unit) → price mapping बनाएं और read करें।
💡 Hint
tuple keys are hashable
✅ Solution
prices = {("apple","kg"):180, ("banana","dozen"):60}
print(prices[("apple","kg")])
P5. List को Dict में बदलें (index → value)
एक list से {index: value} map बनाएं।
💡 Hint
dict(enumerate(list))
✅ Solution
items = ["py","sql","ml"]
m = dict(enumerate(items))
print(m) # {0:'py',1:'sql',2:'ml'}
P6. Dict को value से sort करें (desc)
scores dict को highest→lowest क्रम में list बनाएं।
💡 Hint
sorted(d.items(), key=lambda kv: kv[1], reverse=True)
✅ Solution
scores = {"A":86, "B":92, "C":77}
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(ranked) # [('B',92), ('A',86), ('C',77)]
P7. Config को Tuple में lock करें
(HOST, PORT, DEBUG) record बनाएं और unpack करें।
💡 Hint
tuple & unpacking
✅ Solution
CONFIG = ("localhost", 5432, False)
HOST, PORT, DEBUG = CONFIG
print(HOST, PORT, DEBUG)
P8. Group Names by First Letter (Dict of Lists)
names list को पहले अक्षर से groups में बांटें।
💡 Hint
setdefault(key, []) + append
✅ Solution
names = ["Asha","Aman","Bela","Bharat","Chirag"]
groups = {}
for n in names:
k = n[0].upper()
groups.setdefault(k, []).append(n)
print(groups)
❓ List vs Tuple vs Dictionary – FAQ
Q1: Python में List और Tuple में मुख्य अंतर क्या है?
List mutable होती है यानी इसे बदल सकते हैं, जबकि Tuple immutable होती है और इसे बनाने के बाद बदला नहीं जा सकता।
Q2: Dictionary और List में क्या फर्क है?
List में values को index से access करते हैं, जबकि Dictionary में key से। Dictionary key-value mapping होती है।
Q3: Tuple को List में कैसे बदलें?
my_list = list(my_tuple)
का इस्तेमाल करके Tuple को List में बदला जा सकता है।
Q4: कब List का इस्तेमाल करना चाहिए?
जब data बार-बार update करना हो और order भी maintain करना हो, तब List बेहतर है।
Q5: कब Dictionary का इस्तेमाल करना चाहिए?
जब आपको key-value pairs में fast lookup करना हो, जैसे config data या user profile store करना।
🔗 Related Python Tutorials in Hindi
Python सीखने के लिए हमारे इन अन्य detailed tutorials को भी पढ़ें:
▶️ Python में Loops – For और While
Loops का उपयोग, Syntax और आसान उदाहरण।
▶️ Python में OOPS Concept
Classes, Objects, Inheritance और Polymorphism।
▶️ Python Functions in Hindi
Function types, return statement और syntax।
▶️ Python Operators
Arithmetic, Logical और Comparison operators।
▶️ Python String Handling
String methods, formatting और manipulation।
📢 Python Output — print() Explained (Formatting Tips सहित)
print()
से हम स्क्रीन पर डेटा दिखाते हैं। इस सेक्शन में हम इसके parameters (sep
, end
, file
, flush
)
और formatting (f-strings, width/precision, alignment) सीखेंगे—ताकि python input output in hindi गाइड पूरी बन सके।
print("Hello", "Vista", 2025) # space-separated by default
print("Hello" + " " + "Vista") # manual concat
print("2025","08","11", sep="-") # 2025-08-11
print("Loading", end="...") # same line
print("done") # Loading...done
nums = [1,2,3]
print(*nums, sep=", ") # 1, 2, 3 (unpack)
print(" | ".join(map(str, nums)))# 1 | 2 | 3
name, price, pct = "Course", 2499.9, 0.075
print(f"{name}: ₹{price:.2f}") # ₹2499.90
print(f"Discount: {pct:.1%}") # 7.5%
print(f"|{'left':<10}|{'mid':^10}|{'right':>10}|")
print(f"{1234567:,}") # 1,234,567 (thousands sep)
# Legacy styles:
print("Hi {}, ₹{:.2f}".format("Vista", price))
print("Hi %s, ₹%.2f" % ("Vista", price))
import pprint, json
data = {"user":{"name":"A","skills":["py","sql"],"score":92}}
pprint.pp(data) # pretty for Python objects
print(json.dumps(data, indent=2)) # pretty JSON
# फ़ाइल में आउटपुट
with open("log.txt","w", encoding="utf-8") as f:
print("Hello File", file=f)
# तुरंत स्क्रीन पर फ्लश (e.g., progress)
import time
for i in range(3):
print(i, end=" ", flush=True); time.sleep(0.3)
print("Line1\nLine2") # newline escape
print(r"C:\Users\Vista") # raw string
print("नमस्ते 👋") # Unicode
print("""Multi-line
message with
line breaks""")
⚠️ print बनाम logging
Debug के लिए print()
ठीक है; प्रोडक्शन में logging
module बेहतर है (levels, files, handlers).
⚠️ sep/end भूलना
sep
डिफ़ॉल्ट space है और end
डिफ़ॉल्ट newline। एक ही लाइन पर प्रिंट के लिए end=""
या कस्टम end
यूज़ करें।
⚠️ प्रदर्शन
बहुत बड़ी लिस्ट/स्ट्रिंग को प्रिंट करने से पहले summarize करें; I/O धीमा हो सकता है।
🧪 10 Practice Problems — Input/Output (with Hints & Solutions)
इन problems से आपकी python input output in hindi पकड़ मज़बूत होगी। हर कार्ड में Hint और Solution (Copy-बटन) शामिल है।
P1. दो संख्याओं का जोड़
User से दो numbers लें और sum print करें।
💡 Hint
int(input())
और +
✅ Solution
a = int(input("Enter A: "))
b = int(input("Enter B: "))
print("Sum =", a + b)
P2. One-line Calculator
Input: num1 num2
→ sum, diff, prod, div print करें।
💡 Hint
map(float, input().split())
✅ Solution
x, y = map(float, input("Enter two numbers: ").split())
print("Sum:", x+y, "Diff:", x-y, "Prod:", x*y, "Div:", x/y)
P3. Personalized Greeting
Name और City लें → f-string से output दें।
💡 Hint
f”Hello {name} from {city}”
✅ Solution
name = input("Your name: ")
city = input("Your city: ")
print(f"Hello {name} from {city}! 👋")
P4. N Numbers का Average
Input: n
फिर अगली लाइन में n
numbers → average।
💡 Hint
sum(nums)/len(nums)
✅ Solution
n = int(input("How many numbers? "))
nums = list(map(float, input("Enter numbers: ").split()))
print("Average =", sum(nums)/n)
P5. Km → Miles (formatted)
Km लें और miles (2 decimals) print करें।
💡 Hint
1 km = 0.621371 miles; :.2f
✅ Solution
km = float(input("Enter km: "))
miles = km * 0.621371
print(f"{km:.2f} km = {miles:.2f} miles")
P6. Simple Interest
Input: P, R, T → SI = P*R*T/100; nicely format करें।
💡 Hint
f"₹{si:.2f}"
✅ Solution
P = float(input("Principal: "))
R = float(input("Rate (%): "))
T = float(input("Time (years): "))
si = P*R*T/100
print(f"Simple Interest = ₹{si:.2f}")
P7. Even Numbers Filter
Input list → सिर्फ even numbers को space-separated print करें।
💡 Hint
print(*evens)
या " ".join()
✅ Solution
nums = list(map(int, input("Enter numbers: ").split()))
evens = [n for n in nums if n % 2 == 0]
print(*evens)
P8. टेबल-जैसा Output (Alignment)
तीन items लें और aligned columns में print करें।
💡 Hint
{text:^10}
, {num:>6}
✅ Solution
items = [input("Item1: "), input("Item2: "), input("Item3: ")]
print(f"|{'Item':^10}|{'Len':>6}|")
for it in items:
print(f"|{it:^10}|{len(it):>6}|")
P9. Valid Integer लो (त्रुटि-सुरक्षित)
जब तक user सही integer न दे, पूछते रहें।
💡 Hint
try/except ValueError
✅ Solution
while True:
s = input("Enter an integer: ")
try:
n = int(s)
break
except ValueError:
print("Invalid! Try again.")
print("You entered:", n)
P10. Progress Dots (end + flush)
एक लूप में dots दिखाएँ: ....done
💡 Hint
print(".", end="", flush=True)
✅ Solution
import time
for _ in range(5):
print(".", end="", flush=True); time.sleep(0.3)
print("done")
❓ Python Input/Output — FAQ (Hindi, 2025 Updated)
Q1. input()
क्या वापस करता है? Number कैसे लें?
input()
हमेशा string लौटाता है। Number लेने के लिए type casting करें:
int(input())
, float(input())
.
Q2. एक ही लाइन में multiple inputs कैसे लें?
a, b = input().split()
या numbers के लिए:
a, b = map(int, input().split())
.
Q3. print()
में sep
और end
क्या करते हैं?
sep
arguments के बीच का separator है (डिफ़ॉल्ट space) और end
लाइन के अंत में जोड़ने वाला text है
(डिफ़ॉल्ट newline). जैसे: print(1,2,3, sep=",", end=";")
.
Q4. Output को formatted तरीके से कैसे दिखाएँ?
f-strings सबसे आसान हैं: f"Total: ₹{amount:.2f}"
. Alignment:
{text:^10}
, {num:>6}
; Thousands separator: {n:,}
.
Q5. फ़ाइल में output कैसे लिखें? Encoding का ध्यान?
with open("out.txt","w", encoding="utf-8") as f: print("नमस्ते", file=f)
.
Unicode/हिंदी text के लिए encoding="utf-8"
ज़रूर दें।
Q6. Console में progress/dots तुरंत कैसे दिखाएँ?
print(".", end="", flush=True)
का उपयोग करें ताकि buffer तुरंत flush हो और output live दिखे।
🚀 अब आपकी बारी – Python Skills को अगले लेवल पर ले जाएँ!
आपने Python के input() और print() को अच्छे से सीख लिया है। अब आगे बढ़ें और File Handling, String Manipulation और Operators को मास्टर करें।
📂 Start Next: Python File Handling in Hindi