5-dars: List, Dict, Tuple, Set
Dars
Davomiyligi: 90 daqiqa Maqsad: 4 ta asosiy collection turi va ularning operatsiyalari.
1. List — ro'yxat
python
arr = [10, 20, 30, 40, 50]
mixed = [1, "Akmal", 3.14, True] # turli turlar OK
empty = []C'da — int arr[5]. Python'da — istalgan tur.
2. List operatsiyalari
python
arr = [10, 20, 30, 40, 50]
# Element olish
print(arr[0]) # 10
print(arr[-1]) # 50 (oxiri)
print(arr[1:3]) # [20, 30] (slice)
print(arr[::-1]) # [50, 40, 30, 20, 10] (teskari)
# Uzunlik
print(len(arr)) # 5
# O'zgartirish
arr[0] = 100
# Qo'shish
arr.append(60) # oxirga
arr.insert(0, 5) # boshlanishga
arr.extend([70, 80, 90]) # bir nechta qo'shish
# O'chirish
arr.remove(20) # qiymat bo'yicha
arr.pop() # oxirgisini
arr.pop(0) # index bo'yicha
del arr[1]
arr.clear() # hammasini
# Qidirish
arr.index(30) # joyi
arr.count(30) # necha marta
30 in arr # True/False
# Sort
arr.sort() # in-place
arr.sort(reverse=True)
sorted_arr = sorted(arr) # yangi list3. List slicing
python
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arr[2:5] # [2, 3, 4]
arr[:3] # [0, 1, 2]
arr[7:] # [7, 8, 9]
arr[::2] # [0, 2, 4, 6, 8] (step 2)
arr[::-1] # [9, 8, ..., 0] (teskari)
arr[1:8:2] # [1, 3, 5, 7]4. List comprehension
python
# Oddiy
squares = [x ** 2 for x in range(10)]
# Shart bilan
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[i * j for j in range(3)] for i in range(3)]
# [[0,0,0], [0,1,2], [0,2,4]]
# String'ni transform
words = ["akmal", "aziza", "botir"]
upper = [w.upper() for w in words]5. Tuple
python
t = (1, 2, 3)
print(t[0]) # 1Tuple = o'zgarmas list.
python
t[0] = 100 # XATO! Tuple immutableFoydasi
- Tezroq list'dan
- Xavfsizroq (o'zgarmaydi)
- Function'da bir nechta qiymat qaytarish
- Dict key sifatida ishlatish
Tuple unpacking
python
point = (3, 5)
x, y = point
print(x, y) # 3 5
# Swap
a, b = b, a6. Dict — kalit-qiymat
python
person = {
"name": "Akmal",
"age": 22,
"city": "Toshkent"
}
print(person["name"]) # Akmal
person["age"] = 23 # o'zgartirish
person["email"] = "..." # qo'shish
del person["city"] # o'chirishDict operatsiyalari
python
d = {"a": 1, "b": 2, "c": 3}
# Kalitlar
print(d.keys()) # dict_keys(['a', 'b', 'c'])
print(list(d.keys()))
# Qiymatlar
print(d.values())
# Item'lar (kalit, qiymat)
print(d.items())
# Tekshirish
"a" in d # True
d.get("z", 0) # 0 (default — yo'q bo'lsa)
d.get("a") # 1
# Iteratsiya
for key in d:
print(key, d[key])
for key, value in d.items():
print(key, value)7. Dict comprehension
python
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filter
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}8. Set — to'plam
python
s = {1, 2, 3, 4, 5}
empty = set() # {} — bu dict, set emas!Set — takrorlanmaydigan elementlar.
python
arr = [1, 2, 2, 3, 3, 3, 4]
unique = set(arr) # {1, 2, 3, 4}
unique_list = list(set(arr))Set operatsiyalari
python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # {1,2,3,4,5,6} union
a & b # {3, 4} intersection
a - b # {1, 2} difference
a ^ b # {1,2,5,6} symmetric difference
3 in a # True
a.add(7)
a.remove(1)
a.discard(100) # xato emas (remove — xato)
len(a)Set foydalanish
python
# Duplicate olib tashlash
arr = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(arr))
# Tezkor `in` operatsiyasi
big_list = list(range(1000000))
big_set = set(big_list)
# in list — O(n)
# in set — O(1)9. Taqqoslash
| Tur | Tartibli | Index | O'zgaradi | Takror |
|---|---|---|---|---|
| list | Ha | Ha | Ha | Ha |
| tuple | Ha | Ha | Yo'q | Ha |
| dict | Ha (3.7+) | Kalit | Ha | Kalit — yo'q |
| set | Yo'q | Yo'q | Ha | Yo'q |
10. Nested
python
# List ichida list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6
# Dict ichida dict
users = {
"akmal": {"age": 22, "city": "Toshkent"},
"aziza": {"age": 19, "city": "Samarqand"}
}
print(users["akmal"]["age"]) # 22
# List of dicts
students = [
{"name": "Akmal", "score": 85},
{"name": "Aziza", "score": 92}
]11. Misol: Frequency counter
python
text = "abacabad"
freq = {}
for c in text:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
print(freq) # {'a': 4, 'b': 2, 'c': 1, 'd': 1}Yoki Counter (yaxshiroq):
python
from collections import Counter
freq = Counter(text)
print(freq.most_common(3)) # [('a', 4), ('b', 2), ('c', 1)]12. Misol: Talabalar bazasi
python
students = []
students.append({
"id": 1,
"name": "Akmal",
"age": 22,
"score": 85
})
students.append({
"id": 2,
"name": "Aziza",
"age": 19,
"score": 92
})
# Chiqarish
for s in students:
print(f"{s['name']}: {s['score']}")
# Sort
sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)
# Filter
top = [s for s in students if s["score"] >= 80]
# O'rtacha
avg = sum(s["score"] for s in students) / len(students)13. zip va enumerate
python
names = ["Akmal", "Aziza", "Botir"]
scores = [85, 92, 78]
# zip — birga aylantirish
for name, score in zip(names, scores):
print(f"{name}: {score}")
# enumerate — index bilan
for i, name in enumerate(names):
print(f"{i}: {name}")
# zip'ni dict'ga
d = dict(zip(names, scores))
# {'Akmal': 85, 'Aziza': 92, 'Botir': 78}14. Boshqa foydali
python
# any, all
nums = [1, 2, 3, 4, 0]
any(nums) # True (kamida biri truthy)
all(nums) # False (0 — falsy)
# sum, min, max
sum([1, 2, 3]) # 6
min([3, 1, 2]) # 1
max([3, 1, 2]) # 3
# sorted (yangi list)
sorted([3, 1, 2]) # [1, 2, 3]
sorted([3, 1, 2], reverse=True) # [3, 2, 1]
sorted(["b", "a", "c"]) # ['a', 'b', 'c']
# reversed
list(reversed([1, 2, 3])) # [3, 2, 1]15. Misol: Sotuv tahlili
python
sotuvlar = [
{"mahsulot": "Non", "soni": 15, "narx": 5000},
{"mahsulot": "Sut", "soni": 8, "narx": 12000},
{"mahsulot": "Yog'", "soni": 3, "narx": 45000},
{"mahsulot": "Non", "soni": 20, "narx": 5000},
{"mahsulot": "Sut", "soni": 10, "narx": 12000},
]
# Umumiy daromad
total = sum(s["soni"] * s["narx"] for s in sotuvlar)
print(f"Jami: {total}")
# Mahsulot bo'yicha
mahsulot_summa = {}
for s in sotuvlar:
m = s["mahsulot"]
mahsulot_summa[m] = mahsulot_summa.get(m, 0) + s["soni"] * s["narx"]
for m, s in mahsulot_summa.items():
print(f"{m}: {s}")
# Eng yaxshi
top = max(mahsulot_summa.items(), key=lambda x: x[1])
print(f"Eng yaxshi: {top[0]} ({top[1]})")Topshiriqlar
1 — List asoslari
list_basics.py:
python
arr = [5, 2, 8, 1, 9, 3]
print(arr)
print(len(arr))
print(sum(arr))
print(min(arr), max(arr))
print(sorted(arr))
print(sorted(arr, reverse=True))
print(arr[::-1])2 — List comprehension
comprehension.py — 5 ta turli list comprehension yozing.
3 — Dict mashqi
dict_demo.py:
python
person = {}
person["name"] = input("Ism: ")
person["age"] = int(input("Yosh: "))
person["city"] = input("Shahar: ")
for key, value in person.items():
print(f"{key}: {value}")4 — Frequency
freq.py:
Matn berilgan. Har harfning chastotasini sanang.
Bonus: Counter ishlatish.
5 — Set operatsiyalar
sets.py:
python
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(f"Union: {a | b}")
print(f"Intersection: {a & b}")
print(f"Difference: {a - b}")
print(f"Symmetric diff: {a ^ b}")6 — Duplicate olib tashlash
unique.py:
python
arr = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique = list(set(arr))
print(unique)
# Yoki tartibni saqlash (3.7+)
unique_ordered = list(dict.fromkeys(arr))7 — Talabalar bazasi
students.py:
python
students = [
{"name": "Akmal", "age": 22, "score": 85},
{"name": "Aziza", "age": 19, "score": 92},
{"name": "Botir", "age": 25, "score": 78},
{"name": "Dilshod", "age": 21, "score": 90},
{"name": "Eldor", "age": 20, "score": 65},
]
# Chiqarish
# Sort by score
# Avg score
# Top 3
# Yosh bo'yicha guruhlash8 — zip va dict
zip_demo.py:
python
ismlar = ["Akmal", "Aziza", "Botir"]
yoshlar = [22, 19, 25]
shaharlar = ["Toshkent", "Samarqand", "Buxoro"]
for ism, yosh, shahar in zip(ismlar, yoshlar, shaharlar):
print(f"{ism}, {yosh}, {shahar}")
people = [{"ism": i, "yosh": y, "shahar": s}
for i, y, s in zip(ismlar, yoshlar, shaharlar)]
print(people)9 — Matrix (list of lists)
matrix.py:
python
matrix = [[i * 3 + j + 1 for j in range(3)] for i in range(3)]
# [[1,2,3], [4,5,6], [7,8,9]]
# Print
for row in matrix:
for val in row:
print(f"{val:3}", end=" ")
print()
# Transpose
transposed = [[matrix[j][i] for j in range(3)] for i in range(3)]
# Sum
total = sum(sum(row) for row in matrix)
print(f"Sum: {total}")10 — Hisobot
sotuv.py — Dars matnidagi sotuv tahlili.
Bonus: faylga saqlash.
Lug'at
| Termin | Izoh |
|---|---|
| list | [1, 2, 3] — o'zgaradi |
| tuple | (1, 2, 3) — o'zgarmas |
| dict | {"k": "v"} — kalit-qiymat |
| set | {1, 2, 3} — noyob |
| List comprehension | [x for x in ...] |
| Dict comprehension | {k: v for ...} |
| Slicing | arr[1:5:2] |
in operator | Bormi tekshirish |
enumerate | Index bilan |
zip | Birga aylantirish |
Counter | Chastota |
| Mutable / Immutable | O'zgaradi / o'zgarmaydi |