PythonPython · Chapterبەش 10 · Lectureوانە 10.1
Tuples, Sets and Dictionariesتاپڵەکان، کۆمەڵەکان و فەرهەنگەکان
Three more ways to keep many values in Python: tuples (fixed groups you can unpack), sets (no duplicates, fast in, union and intersection) and dictionaries (find a value by its key, count things, keep a marks book).
سێ ڕێگای تر بۆ هەڵگرتنی چەندین لە : (کۆمەڵەی جێگیر کە دەتوانیت بیانکەیتەوە)، (بێ دووبارە، inـی خێرا، و ) و ( بە بدۆزەرەوە، شت بژمێرە، دەفتەری نمرە ڕێک بخە).
What you will learnچی فێر دەبیت
- Create tuples, read them by index and explain why they cannot change.
- Pack and unpack values, swap two variables and return several results from a function.
- Use sets to remove duplicates, test membership and combine groups with
|,&,-and^. - Build, change and loop over dictionaries, and read missing keys safely with
inandget(). - Count things and keep records (a marks book) with a dictionary, and choose the right structure for a task.
- دروست بکەیت، بە بیانخوێنیتەوە و ڕوونی بکەیتەوە بۆچی ناگۆڕدرێن.
- بپێچیتەوە و بکەیتەوە، دوو بگۆڕیتەوە و چەند ئەنجامێک لە بگەڕێنیتەوە.
- بەکار بهێنیت بۆ لابردنی دووبارە، پشکنینی ئەندامێتی و تێکەڵکردنی کۆمەڵەکان بە
|،&،-و^. - دروست بکەیت، بیانگۆڕیت و بەسەردا بکەیت و کە نین بە
inوget()بە سەلامەتی بخوێنیتەوە. - بە شت بژمێریت و تۆمار هەڵبگریت (دەفتەری نمرە) و گونجاو بۆ کارێک هەڵبژێریت.
Four ways to keep many valuesچوار ڕێگا بۆ هەڵگرتنی چەندین نرخ
You already know the list: a row of values in order that you can change at any time. Python has three more built-in data structures for a group of values. Each one is good at a different job:
دەناسیت: ڕیزێکی ڕێکخراوی کە هەر کاتێک بتەوێت دەتوانیت بیگۆڕیت. سێ ئامادەی تریشی هەیە بۆ کۆمەڵێک . هەر یەکەیان بۆ کارێکی جیاواز باشە:
- Tuple
(23, 10, 2026): a fixed row of values. Once it is made, it never changes. - Set
{"Aram", "Shilan"}: a bag of different values. It has no order and no duplicates. - Dictionary
{"tea": 500}: pairs of key → value. You find a value by its key, the way you find a word's meaning in a book dictionary.
-
(23, 10, 2026): ڕیزێکی جێگیری . کە دروست کرا، هەرگیز ناگۆڕێت. -
{"Aram", "Shilan"}: کیسەیەک لە جیاواز. نە ڕیزبەندیی هەیە و نە دووبارە. -
{"tea": 500}: . بە دەدۆزیتەوە، هەروەک چۆن واتای وشەیەک لە فەرهەنگێکی کتێبیدا دەدۆزیتەوە.
This lesson follows chapter 5 of the official Python tutorial and the matching parts of two well-known beginner courses (CS50's Python course and Liang's textbook). It is extra material: the course notes stop at lists.
ئەم وانەیە بەدوای بەشی 5ی ڕێنمایی فەرمیی و بەشە هاوتاکانی دوو کۆرسی ناسراوی سەرەتایی (کۆرسی Pythonـی CS50 و کتێبەکەی Liang) دەڕوات. ئەمە بابەتێکی زیادەیە: تێبینییەکانی کۆرسەکە لە دەوەستن.
Tuples: values that stay fixedتاپڵەکان: نرخەکان کە جێگیر دەمێننەوە
A tuple is written with round brackets and commas. Like a list, it keeps its items in order, so indexes, negative indexes, len(), in and a for loop all work the same way:
بە کەوانەی خڕ و کۆما دەنووسرێت. وەک ، بە ڕیز دەپارێزێت، بۆیە ، ، len()، in و هەموویان بە هەمان شێوە کار دەکەن:
today = (23, 10, 2026) # day, month, year
point = (3, 4) # x, y
print(today)
print(today[0], today[-1])
print(len(today), 2026 in today)
for part in point:
print(part)(23, 10, 2026) 23 2026 3 True 3 4
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-2
Round brackets and commas make two tuples. The comment says what each position means.
کەوانەی خڕ و کۆما دوو دروست دەکەن. لێدوانەکە دەڵێت هەر شوێنێک واتای چییە.
- Lineدێڕی 4
Index
0is the first item and-1the last, exactly as in a list or a string.0یەکەم و-1دواینە، ڕێک وەک یان .
A Python collection like a list that cannot be changed after it is made, written in round brackets: (6, 0). Tuples are often used for positions and for the (priority, count, item) entries of a heap.
کۆکراوەیەکی وەک ، بەڵام دوای دروستکردنی ناگۆڕدرێت، لەناو کەوانەی ئاساییدا دەنووسرێت: (6, 0). زۆرجار بۆ شوێنی خانەکان و بۆ تۆمارەکانی (پێشینەیی، ژمارە، دانە)ی بەکار دێت.
The big difference from a list: a tuple is immutable. After it is made you cannot change, add or remove an item. If you try, Python stops with a TypeError:
جیاوازییە گەورەکە لەگەڵ : . دوای دروستکردنی ناتوانیت بگۆڕیت، زیاد بکەیت یان لابەریت. ئەگەر هەوڵ بدەیت، بە TypeError دەوەستێت:
today = (23, 10, 2026)
today[0] = 24Traceback (most recent call last):
File "change_tuple.py", line 2, in <module>
today[0] = 24
~~~~~^^^
TypeError: 'tuple' object does not support item assignmentWhy would anyone want a row of values that cannot change? Because some data should never change by mistake: a date, a position (row, column), the size of a board. A tuple also tells the reader these values belong together and stay as they are. And because it cannot change, a tuple can be a dictionary key (you will see this later in the lesson); a list cannot.
بۆچی کەسێک ڕیزێک دەوێت کە ناگۆڕدرێت؟ چونکە هەندێک نابێت هەرگیز بە هەڵە بگۆڕێت: بەروارێک، شوێنێک (row, column)، قەبارەی تەختەیەک. هەروەها بە خوێنەر دەڵێت ئەم پێکەوەن و وەک خۆیان دەمێننەوە. لەبەر ئەوەی ناگۆڕێت، دەتوانێت ببێتە (لە درێژەی وانەکەدا دەیبینیت)؛ بەڵام ناتوانێت.
Tuples: values that stay fixedتاپڵەکان: نرخەکان کە جێگیر دەمێننەوە
The comma makes the tupleکۆماکە تاپڵەکە دروست دەکات
Here is a surprise: the round brackets do not make a tuple, the commas do. (5) is just the number 5 inside brackets, as in maths. For a tuple with one item, put a comma after the item: (5,). Even 5, without brackets is a tuple. An empty tuple is ().
ئەمە سەرسوڕهێنەرە: کەوانە خڕەکان دروست ناکەن، بەڵکو کۆماکان دروستی دەکەن. (5) تەنها ژمارە 5ـە لەناو کەوانەدا، وەک لە بیرکاریدا. بۆ کە یەک هەبێت، کۆمایەک دوای دابنێ: (5,). تەنانەت 5, بەبێ کەوانەش . بەتاڵ ()ـە.
a = (5)
b = (5,)
c = 5,
empty = ()
print(type(a), type(b), type(c))
print(b, c, len(empty))<class 'int'> <class 'tuple'> <class 'tuple'> (5,) (5,) 0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Only brackets: an
int, not a tuple.تەنها کەوانە:
intـە، نەک .- Lineدێڕی 2-3
The comma turns the value into a one-item tuple.
کۆماکە دەکات بە کە یەک هەیە.
Tuples: values that stay fixedتاپڵەکان: نرخەکان کە جێگیر دەمێننەوە
New tuples from old: +, * and slicesدروستکردنی تاپڵی نوێ لە کۆنەکان: +، * و لەتکردن
A tuple never changes, but you can build new tuples from it. + joins two tuples, * repeats one and a slice gives a shorter tuple; in and not in work as with lists. Even += does not change a tuple: it builds a new one and moves the name to it. id() (Every value is an object with an id) shows this:
هەرگیز ناگۆڕێت، بەڵام دەتوانیت نوێ لێی دروست بکەیت. + دوو پێکەوە دەلکێنێت، * دووبارە دەکاتەوە و کورتتر دەدات؛ in و not in وەک لە کار دەکەن. تەنانەت +=ـیش ناگۆڕێت: نوێ دروست دەکات و ناوەکە دەباتە سەری. id() (هەموو نرخێک ئۆبجێکتێکە و ناسنامەی هەیە) ئەمە پیشان دەدات:
point = (3, 4)
bigger = point + (5,) # + joins two tuples into a new one
print(bigger, point)
print((0, 1) * 3) # * repeats a tuple
print(bigger[1:], 4 in bigger, 9 not in bigger)
before = id(point)
point += (5,) # builds a new tuple, then point names it
print(point, id(point) == before)(3, 4, 5) (3, 4) (0, 1, 0, 1, 0, 1) (4, 5) True True (3, 4, 5) False
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
+makes a new tuple;pointitself is still(3, 4).+نوێ دروست دەکات؛pointخۆی هێشتا(3, 4)ـە.- Lineدێڕی 5
A slice of a tuple is a tuple.
هەر .
- Lineدێڕی 6-8
False: after+=the namepointbelongs to a different object.False: دوای+=ناویpointهی ترە.
Tuples: values that stay fixedتاپڵەکان: نرخەکان کە جێگیر دەمێننەوە
Functions and the two tuple methodsکردارەکان و دوو میتۆدەکەی تاپڵ
len(), min(), max() and sum() work on tuples just as on lists. A tuple has only two methods, because it cannot change: count(x) says how often x appears and index(x) gives the position of the first x. There is no append() and no sort(). sorted() still works, but it always returns a list, and tuple() turns a list, a string or a range into a tuple:
len()، min()، max() و sum() لەسەر وەک کار دەکەن. تەنها دوو هەیە، چونکە ناگۆڕێت: count(x) دەڵێت x چەند جار هاتووە و index(x) شوێنی یەکەم x دەدات. append() و sort()ـی نییە. sorted() هەر کار دەکات، بەڵام هەمیشە دەگەڕێنێتەوە و tuple() ، یان rangeـێک دەکات بە :
marks = (78, 91, 64, 91)
print(len(marks), min(marks), max(marks), sum(marks))
print(marks.count(91), marks.index(64))
in_order = sorted(marks) # sorted() always gives a list
print(in_order, marks)
print(tuple(in_order), tuple("tea"), tuple(range(3)))4 64 91 324
2 2
[64, 78, 91, 91] (78, 91, 64, 91)
(64, 78, 91, 91) ('t', 'e', 'a') (0, 1, 2)Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
91 appears twice; 64 sits at index 2.
91 دوو جار هاتووە؛ 64 لەسەر 2ـە.
- Lineدێڕی 4-5
sorted()gives a new list; the tuplemarksis unchanged.sorted()نوێ دەدات؛marksوەک خۆی دەمێنێتەوە.- Lineدێڕی 6
tuple()builds a tuple from a list, a string or a range.tuple()لە ، یانrangeـێک دروست دەکات.
Tuples: values that stay fixedتاپڵەکان: نرخەکان کە جێگیر دەمێننەوە
Fixed, but not frozen: a list inside a tupleجێگیر، بەڵام بەستوو نا: لیستێک لەناو تاپڵێکدا
A tuple's own slots are fixed: you cannot put a different item into a slot. But when a slot holds a list, that list can still grow or change:
خانەکانی خودی جێگیرن: ناتوانیت تر بخەیتە خانەیەکەوە. بەڵام کاتێک خانەیەک تێدایە، ئەو هێشتا دەتوانێت گەورە ببێت یان بگۆڕێت:
student = ("Aram", [78, 85])
student[1].append(90) # the list inside the tuple can change
print(student)
student[1] = [100] # the tuple itself cannot('Aram', [78, 85, 90])
Traceback (most recent call last):
File "list_in_tuple.py", line 4, in <module>
student[1] = [100] # the tuple itself cannot
~~~~~~~^^^
TypeError: 'tuple' object does not support item assignmentExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
student[1]is the list;append()changes the list, not the tuple.student[1]؛append()دەگۆڕێت نەک .- Lineدێڕی 4
Putting a new item into a tuple slot is still a
TypeError.دانانی نوێ لە خانەیەکی هێشتا
TypeErrorـە.
Such a tuple is not really unchangeable, so it cannot be a dictionary key either (What can be a key?). For a record that must never change, use only immutable items inside: numbers, strings and tuples.
وا بە ڕاستی نییە، بۆیە ناشتوانێت ببێتە (چی دەتوانێت ببێتە کلیل؟). بۆ تۆمارێک کە هەرگیز نابێت بگۆڕێت، تەنها بخەرە ناوی: ژمارە، و .
Packing, unpacking and swappingپێچانەوە، کردنەوە و گۆڕینەوە
When you write values with commas, Python packs them into a tuple: point = 3, 4. The opposite is unpacking: one assignment gives every value its own variable, x, y = point. Python's documentation calls this sequence unpacking; many languages call it .
کاتێک چەند بە کۆما دەنووسیت، دەیانپێچێتەوە لە : point = 3, 4. پێچەوانەکەی کردنەوەیە: یەک دانان هەر دەخاتە تایبەتی خۆیەوە، x, y = point. بەڵگەنامەکانی پێی دەڵێن کردنەوەی ؛ زۆر زمانیش پێی دەڵێن .
point = 3, 4 # packing: the commas make a tuple
x, y = point # unpacking: one name for each item
print(x, y)
a = "tea"
b = "coffee"
a, b = b, a # swap without a third variable
print(a, b)3 4 coffee tea
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The commas pack 3 and 4 into the tuple
(3, 4).کۆماکان 3 و 4 لە
(3, 4)ـدا دەپێچنەوە.- Lineدێڕی 2
Unpacking:
xgets 3 andygets 4.کردنەوە:
x3 وەردەگرێت وy4.- Lineدێڕی 7
The swap. Python first builds the tuple on the right,
("coffee", "tea"), then unpacks it intoaandb.گۆڕینەوەکە. سەرەتا لای ڕاست دروست دەکات،
("coffee", "tea")، پاشان دەیکاتەوە بۆaوb.
In many other languages a swap needs a third variable (temp = a, a = b, b = temp). In Python one line is enough, because the whole right side is evaluated before anything is assigned.
لە زۆر زمانی تردا گۆڕینەوە پێویستی بە سێیەم هەیە (temp = a، a = b، b = temp). لە یەک دێڕ بەسە، چونکە هەموو لای ڕاست پێش دانانی هەر هەژمار دەکرێت.
Packing, unpacking and swappingپێچانەوە، کردنەوە و گۆڕینەوە
A function can return a tupleکردار دەتوانێت تاپڵێک بگەڕێنێتەوە
You saw in Return values that a function can return several values with one return. Now you know what really happens: the values are packed into one tuple, and the caller can unpack it.
لە نرخە گەڕاوەکان بینیت کە دەتوانێت بە یەک return چەند بگەڕێنێتەوە. ئێستا دەزانیت لە ڕاستیدا چی ڕوو دەدات: لە یەک دەپێچرێنەوە و بانگکەر دەتوانێت بیکاتەوە.
def lowest_and_highest(marks):
return min(marks), max(marks)
result = lowest_and_highest([78, 91, 64, 85])
print(result)
low, high = result
print("Lowest:", low, "Highest:", high)(64, 91) Lowest: 64 Highest: 91
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
min(marks), max(marks)is a tuple of two values.min(marks), max(marks)کە دوو تێدایە.- Lineدێڕی 6-7
Printing the result shows the tuple; unpacking gives two variables.
چاپکردنی ئەنجامەکە پیشان دەدات؛ کردنەوەکەش دوو دەدات.
Unpacking needs exactly one name for every value. With too few or too many names Python stops with a ValueError:
کردنەوە ڕێک یەک ناوی بۆ هەر پێویستە. ئەگەر ناوەکان کەمتر یان زیاتر بن، بە ValueError دەوەستێت:
day, month = (23, 10, 2026)Traceback (most recent call last):
File "unpack_error.py", line 1, in <module>
day, month = (23, 10, 2026)
^^^^^^^^^^
ValueError: too many values to unpack (expected 2)Tuple or list?تاپڵ یان لیست؟
Both keep values in order. Choose by asking one question: will this group change while the program runs?
هەردووکیان بە ڕیز دەپارێزن. بە یەک پرسیار هەڵبژێرە: ئایا ئەم کۆمەڵە لە کاتی کارکردنی دەگۆڕێت؟
| Questionپرسیار | List | Tuple |
|---|---|---|
| Written withبە چی دەنووسرێت | [78, 91, 64] | (23, 10, 2026) |
| Can change?دەگۆڕدرێت؟ | Yes: append(), remove(), x[0] = …بەڵێ: append()، remove()، x[0] = … | No (immutable)نەخێر () |
| Typical useبەکارهێنانی باو | Many values of the same kind that grow or shrink: marks, namesزۆر لە یەک جۆر کە زیاد و کەم دەکەن: نمرەکان، ناوەکان | A small fixed record: a date, (row, column), a function's resultsتۆمارێکی بچووکی جێگیر: بەروار، (row, column)، ئەنجامەکانی |
| Dictionary key? ؟ | Noنەخێر | Yesبەڵێ |
Sets: no duplicates, no orderکۆمەڵەکان: بێ دووبارە و بێ ڕیز
A set holds different values, each one only once. Write it with curly braces, or turn a list into a set with set(). Duplicates disappear by themselves, which makes a set the quickest way to answer how many different…?
جیاواز هەڵدەگرێت و هەر یەکەیان تەنها یەک جار. بە کەوانەی لوولپێچ دەینووسیت، یان بە set() دەکەیت بە . دووبارەکان خۆیان لادەچن، بۆیە خێراترین ڕێگایە بۆ وەڵامی چەند … ی جیاواز هەیە؟
visitors = ["Aram", "Shilan", "Aram", "Karwan", "Shilan"]
unique = set(visitors)
print(len(visitors), len(unique))
print(sorted(unique))
print("Karwan" in unique, "Dilan" in unique)
print({3, 1, 3, 2, 1})5 3
['Aram', 'Karwan', 'Shilan']
True False
{1, 2, 3}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Five names go in; the set keeps each name once.
پێنج ناو دەچنە ناوەوە؛ هەر ناوێک یەک جار دەهێڵێتەوە.
- Lineدێڕی 4
sorted()gives a list in alphabetical order, because a set itself has no order.sorted()بە ڕیزی ئەلفوبێ دەدات، چونکە خۆی ڕیزی نییە.- Lineدێڕی 5
inasks is this value in the set? For a set this is very fast, even with a million items.inدەپرسێت ئایا ئەم لە هەیە؟ بۆ ئەمە زۆر خێرایە، تەنانەت بە ملیۆنێک .- Lineدێڕی 6
Duplicates vanish here too: 3 and 1 were written twice.
لێرەش دووبارەکان نامێنن: 3 و 1 دوو جار نووسرابوون.
A collection of different values with no order: {1, 2, 3} in Python, {1, 2, 3} as a Set in Dart. A value is either in the set or not, and checking that is very fast, so search code often keeps the explored set in one.
کۆکراوەیەکی نرخی جیاوازە بەبێ ڕیزبەندی: لە Pythonـدا {1, 2, 3} و لە Dartـدا {1, 2, 3} وەک Set. نرخێک یان لەناو کۆمەڵەکەدایە یان نییە و پشکنینی ئەمە زۆر خێرایە، بۆیە کۆدی گەڕان زۆرجار تێیدا هەڵدەگرێت.
No order means more than "not sorted". A set has no first or last item, so s[0] is an error (TypeError: 'set' object is not subscriptable). Printing a set of names can even show a different order each time the program starts. Here is the same one-line program, run three times in a row:
بێ ڕیز زیاتر لە "ڕیز نەکراو" دەگەیەنێت. یەکەم و دوایینی نییە، بۆیە s[0] (TypeError: 'set' object is not subscriptable). چاپکردنی ناو تەنانەت دەکرێت لە هەر جارێکی دەستپێکردنی ڕیزێکی جیاواز پیشان بدات. ئەمە هەمان یەک دێڕییە کە سێ جار لە دوای یەک کاری پێ کراوە:
print({"Aram", "Shilan", "Karwan"}){'Shilan', 'Aram', 'Karwan'}
{'Aram', 'Shilan', 'Karwan'}
{'Aram', 'Karwan', 'Shilan'}Your order may be different again: Python mixes the order of text in sets on purpose for safety.
لەوانەیە ڕیزبەندیی تۆ دیسان جیاواز بێت: بە ئەنقەست بۆ پاراستن ڕیزی دەق لە تێکەڵ دەکات.
Sets: no duplicates, no orderکۆمەڵەکان: بێ دووبارە و بێ ڕیز
Adding and removingزیادکردن و لابردن
A set itself can change: add() puts a value in (nothing happens if it is already there), discard() takes it out quietly, and remove() takes it out but raises KeyError when the value is missing. Watch out for one trap: {} is an empty dictionary, so an empty set must be written set().
خۆی دەگۆڕدرێت: add() دەخاتە ناوەوە (ئەگەر پێشتر هەبێت هیچ ڕوو نادات)، discard() بە بێدەنگی دەریدەهێنێت و remove() دەریدەهێنێت بەڵام ئەگەر نەبێت KeyError دروست دەکات. ئاگاداری داوێک بە: {} بەتاڵە، بۆیە بەتاڵ دەبێت بە set() بنووسرێت.
seen = {0, 1}
seen.add(1) # already there: nothing changes
seen.add(2)
print(seen)
seen.discard(5) # not there: discard() is quiet
seen.remove(2)
print(seen)
print(type({}), type(set()))
seen.remove(7) # not there: remove() raises KeyError{0, 1, 2}
{0, 1}
<class 'dict'> <class 'set'>
Traceback (most recent call last):
File "set_changes.py", line 9, in <module>
seen.remove(7) # not there: remove() raises KeyError
^^^^^^^^^^^^^^
KeyError: 7Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
1 is already in the set, so nothing changes.
1 پێشتر لە هەیە، بۆیە هیچ ناگۆڕێت.
- Lineدێڕی 8
{}makes a dict; onlyset()makes an empty set.{}دروست دەکات؛ تەنهاset()بەتاڵ دروست دەکات.- Lineدێڕی 9
remove()of a missing value stops the program. Usediscard()when the value may be missing.remove()ـی کە نییە دەوەستێنێت. کاتێک لەوانەیە نەبێتdiscard()بەکار بهێنە.
Sets: no duplicates, no orderکۆمەڵەکان: بێ دووبارە و بێ ڕیز
Union, intersection and differenceیەکگرتن، یەکتربڕین و جیاوازیی کۆمەڵە
Python sets know the operations of mathematical sets. Here two school clubs are two sets of students. The maths behind them (Venn diagrams, the signs ∪ and ∩) is explained in Union, intersection, difference and complement; here we only use them in code.
ئەو کارانە دەزانن کە لە بیرکاریدا لەسەر دەکرێن. لێرەدا دوو یانەی قوتابخانە دوو قوتابین. بیرکارییەکەی پشتیان ( و نیشانەکانی ∪ و ∩) لە یەکگرتن، یەکتربڕین، جیاوازیی کۆمەڵە و تەواوکەر ڕوون کراوەتەوە؛ لێرە تەنها لە کۆددا بەکاریان دەهێنین.
football = {"Aram", "Shilan", "Karwan", "Dilan"}
chess = {"Shilan", "Rezan", "Dilan", "Hana"}
print(sorted(football | chess)) # in either club (or both)
print(sorted(football & chess)) # in both clubs
print(sorted(football - chess)) # in football but not chess
print(sorted(football ^ chess)) # in exactly one club['Aram', 'Dilan', 'Hana', 'Karwan', 'Rezan', 'Shilan'] ['Dilan', 'Shilan'] ['Aram', 'Karwan'] ['Aram', 'Hana', 'Karwan', 'Rezan']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
|(union): everyone in at least one club.|(): هەموو ئەوانەی لانیکەم لە یانەیەکدان.- Lineدێڕی 4
&(intersection): only those in both clubs.&(): تەنها ئەوانەی لە هەردوو یانەکەدان.- Lineدێڕی 5
-(difference): in football but not in chess.chess - footballwould give Hana and Rezan.-(): لە تۆپی پێدان بەڵام لە شەترەنجدا نین.chess - footballHana و Rezan دەدات.- Lineدێڕی 6
^(symmetric difference): in exactly one of the two clubs.^(): ڕێک لە یەکێک لە دوو یانەکەدا.
| Python | Meaningواتا | Mathsبیرکاری | Method formشێوەی |
|---|---|---|---|
a | b | in a, in b or in bothلە a، لە b یان لە هەردووکیاندا | a.union(b) | |
a & b | in both a and bلە هەردووکی a و bـدا | a.intersection(b) | |
a - b | in a but not in bلە aـدا بەڵام لە bـدا نا | a.difference(b) | |
a ^ b | in exactly one of themڕێک لە یەکێکیاندا | a.symmetric_difference(b) | |
a <= b | every item of a is also in b (subset)هەموو a لە bـیشدا هەیە () | a.issubset(b) |
In Kurdish: a tuple in round brackets that cannot be changed, then sets in curly braces with union, intersection and difference.
بە کوردی: لەناو کەوانەی ئاسایی ()دا دەنووسرێت و ناگۆڕدرێت. پاشان فێری دەبیت کە لەناو کەوانەی لوولی {}دا دەنووسرێن، لەگەڵ ، و .
In Sorani, plays 5:50–10:15: two sets in PyCharm, then union(), difference(), symmetric_difference() and the operators & and ^.
بە سۆرانی، لە 5:50 تا 10:15 پەخش دەبێت: دوو لە PyCharmـدا، پاشان union()، difference()، symmetric_difference() و & و ^.
Sets: no duplicates, no orderکۆمەڵەکان: بێ دووبارە و بێ ڕیز
A set as a quick checkکۆمەڵە وەک پشکنینێکی خێرا
Turning a string into a set gives the different characters in it. Together with <= (subset) this is a neat way to check user input: are all the characters allowed ones? The binary converter project uses this idea.
گۆڕینی بۆ ئەو جیاوازانە دەدات کە تێیدان. لەگەڵ <= () ئەمە ڕێگایەکی ڕێکە بۆ پشکنینی : ئایا هەموو ڕێگەپێدراون؟ پڕۆژەی گۆڕینی ئەم بیرۆکەیە بەکار دەهێنێت.
allowed = {"0", "1"}
for text in ["101", "1021", "0110"]:
print(text, set(text) <= allowed)101 True 1021 False 0110 True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
set("1021")is{'0', '1', '2'}. Because'2'is not allowed, the subset test is False.set("1021")دەکاتە{'0', '1', '2'}. لەبەر ئەوەی'2'ڕێگەپێدراو نییە، پشکنینیFalseـە.
You will use this check in Project: Binary to Decimal Converter.
ئەم پشکنینە لە پڕۆژیلە: گۆڕینی دووانی بۆ دەیی بەکار دەهێنیت.
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
On the wall of a tea house there is a board: tea 500, bread 250, sugar 1500. You do not read it from the top to find the price of bread; you look for the word bread and read the number next to it. The word is the key, the number is its value.
لەسەر دیواری چایخانەیەک تەختەیەک هەیە: چا 500، نان 250، شەکر 1500. بۆ دۆزینەوەی نرخی نان لە سەرەوە نایخوێنیتەوە؛ بەدوای وشەی ناندا دەگەڕێیت و ژمارەکەی تەنیشتی دەخوێنیتەوە. وشەکە و ژمارەکە ـە.
Where the analogy stops workingسنووری ئەم نموونەیە
On a board the same word could be written twice by mistake. In a dictionary every key appears only once: writing a key again replaces its old value.
لەسەر تەختە دەکرێت هەمان وشە بە هەڵە دوو جار بنووسرێت. لە هەر تەنها یەک جار هەیە: دووبارە نووسینەوەی کۆنەکەی دەگۆڕێت.
A Python dictionary is written with curly braces and key: value pairs. You read a value with square brackets and the key, prices["bread"], not with a position number.
بە کەوانەی لوولپێچ و جووتی key: value دەنووسرێت. بە کەوانەی چوارگۆشە و دەخوێنیتەوە، prices["bread"]، نەک بە ژمارەی شوێن.
prices = {"tea": 500, "bread": 250, "sugar": 1500} # item -> dinars
print(prices["bread"])
print(len(prices))
print("tea" in prices, 500 in prices)
print(prices)250
3
True False
{'tea': 500, 'bread': 250, 'sugar': 1500}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Three pairs. The keys are strings; the values are numbers (dinars).
سێ جووت. ؛ ژمارەن (دینار).
- Lineدێڕی 2
Look up the value of the key
"bread"."bread"دەدۆزێتەوە.- Lineدێڕی 4
inchecks the keys only. 500 is a value, not a key, so the answer isFalse.inتەنها دەپشکنێت. 500 نەک ، بۆیە وەڵامەکەFalseـە.
![An animation. A dictionary of marks is drawn as a table: Aram 78, Shilan 91, Karwan 64. The code marks["Shilan"] appears; an arrow goes straight to the row with the key Shilan, which lights up, and 91 is printed. Then marks["Dilan"] is asked: there is no such key and KeyError: 'Dilan' appears in red. Last, marks.get("Dilan", "no mark") prints no mark instead of stopping.](/_astro/py-tuples-sets-dictionaries-lookup.en.BsLMurgo.gif)
![An animation. A dictionary of marks is drawn as a table: Aram 78, Shilan 91, Karwan 64. The code marks["Shilan"] appears; an arrow goes straight to the row with the key Shilan, which lights up, and 91 is printed. Then marks["Dilan"] is asked: there is no such key and KeyError: 'Dilan' appears in red. Last, marks.get("Dilan", "no mark") prints no mark instead of stopping.](/_astro/py-tuples-sets-dictionaries-lookup.ckb.MItWIR2J.gif)
get() بەکار بهێنیت.CêITA Python collection of key–value pairs written in curly braces, such as {'name': 'Aram', 'age': 20}. You look up a value by its key, like looking up a word in a dictionary.
کۆکراوەیەکی لە کە لەناو {}دا دەنووسرێت، وەک {'name': 'Aram', 'age': 20}. نرخێک بە دەدۆزیتەوە، وەک دۆزینەوەی وشەیەک لە فەرهەنگدا.
A short Kurdish (Sorani) introduction to Python dictionaries: keys, values and what you can do with a dictionary.
ناساندنێکی کورتی کوردی (سۆرانی) بۆ لە : ، و ئەوەی دەتوانیت بە بیکەیت.
Kurdish (Sorani) video, under 4 minutes: Python dictionaries for beginners.
ڤیدیۆیەکی کوردی (سۆرانی)، کەمتر لە 4 خولەک: لە بۆ سەرەتاییەکان.
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
When the key is missingکاتێک کلیلەکە نییە
Asking for a key that is not in the dictionary stops the program with a KeyError:
داواکردنی کە لە نییە بە KeyError دەوەستێنێت:
prices = {"tea": 500, "bread": 250, "sugar": 1500}
print(prices["milk"])Traceback (most recent call last):
File "missing_key.py", line 2, in <module>
print(prices["milk"])
~~~~~~^^^^^^^^
KeyError: 'milk'There are three ways to stay safe. Check first with if "milk" in prices:. Or use prices.get("milk"), which gives None instead of an error, or prices.get("milk", 0), which gives your own default. Or catch the KeyError with try and except, as the next lesson, Handling errors, shows.
سێ ڕێگا هەیە بۆ سەلامەت مانەوە. سەرەتا بە if "milk" in prices: بپشکنە. یان prices.get("milk") بەکار بهێنە کە لەبری None دەدات، یان prices.get("milk", 0) کە خۆت دەدات. یان KeyError بە try و except بگرە، وەک وانەی داهاتوو مامەڵەکردن لەگەڵ هەڵەکان پیشانی دەدات.
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
Adding, changing and removingزیادکردن، گۆڕین و لابردن
A dictionary is mutable. One line does two jobs: prices[key] = value adds a new pair when the key is new, and replaces the value when the key already exists. del and pop() remove a pair.
. یەک دێڕ دوو کار دەکات: prices[key] = value ئەگەر نوێ بێت جووتێکی نوێ زیاد دەکات و ئەگەر پێشتر هەبێت دەگۆڕێت. del و pop() جووتێک لادەبەن.
prices = {"tea": 500, "bread": 250}
prices["sugar"] = 1500 # new key: a new pair is added
prices["tea"] = 750 # old key: the value is replaced
del prices["bread"] # remove a pair
print(prices)
print(prices.get("milk")) # missing key: None
print(prices.get("milk", 0)) # missing key: the default 0
print(prices.pop("sugar"), prices){'tea': 750, 'sugar': 1500}
None
0
1500 {'tea': 750}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
"sugar"is new: a pair is added at the end."sugar"نوێیە: جووتێک لە کۆتاییدا زیاد دەکرێت.- Lineدێڕی 3
"tea"exists: 500 is replaced by 750. Keys never repeat."tea"هەیە: 500 بە 750 دەگۆڕدرێت. هەرگیز دووبارە نابنەوە.- Lineدێڕی 8
pop()removes the pair and gives back its value.pop()جووتەکە لادەبات و دەگەڕێنێتەوە.
| You writeدەنووسیت | It doesچی دەکات |
|---|---|
d[key] | the value; KeyError if the key is missing؛ ئەگەر نەبێت KeyError |
d[key] = value | add a new pair, or replace the old valueجووتێکی نوێ زیاد دەکات، یان کۆنەکە دەگۆڕێت |
d.get(key, default) | the value, or the default when the key is missing، یان کاتێک نییە |
key in d | True if the key exists (keys only)ئەگەر هەبێت True (تەنها ) |
del d[key] | remove the pairجووتەکە لادەبات |
d.pop(key) | remove the pair and return its valueجووتەکە لادەبات و دەگەڕێنێتەوە |
len(d) | the number of pairsژمارەی جووتەکان |
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
More ways to build and change a dictionaryڕێگای تری دروستکردن و گۆڕینی فەرهەنگ
dict() builds a dictionary from a list of (key, value) pairs, or from keyword arguments when the keys are simple words. update() copies every pair of another dictionary in: new keys are added and existing keys get the new value. clear() removes all pairs at once.
dict() لە جووتی (key, value) دروست دەکات، یان لە کاتێک وشەی سادەن. update() هەموو جووتەکانی تر دەخاتە ناوەوە: نوێ زیاد دەکرێن و هەبوو نوێ وەردەگرن. clear() هەموو جووتەکان پێکەوە لادەبات.
pairs = [("tea", 500), ("bread", 250)]
prices = dict(pairs) # from a list of (key, value) pairs
print(prices)
extra = dict(sugar=1500, tea=750) # from keyword arguments
prices.update(extra) # add new pairs, replace old values
print(prices)
prices.clear() # remove every pair
print(prices, len(prices)){'tea': 500, 'bread': 250}
{'tea': 750, 'bread': 250, 'sugar': 1500}
{} 0Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Each tuple in the list becomes one pair.
هەر لە دەبێتە جووتێک.
- Lineدێڕی 4-5
sugaris new and is added;teaexists, so 500 becomes 750.sugarنوێیە و زیاد دەکرێت؛teaهەیە، بۆیە 500 دەبێتە 750.- Lineدێڕی 7-8
An empty dictionary prints as
{}and has length 0.بەتاڵ وەک
{}چاپ دەبێت و درێژییەکەی 0ـە.
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
Looping over a dictionaryخول بەسەر فەرهەنگێکدا
A for loop over a dictionary gives its keys. To get key and value together, loop over items(): each item is a (key, value) tuple that you unpack into two variables. keys() and values() give only one side. Since Python 3.7 a dictionary always remembers the order in which the keys were added.
بەسەر دەدات. بۆ وەرگرتنی و پێکەوە، بەسەر items()ـدا بکە: هەر یەکێکیان (key, value)ـە کە دەیکەیتەوە بۆ دوو . keys() و values() تەنها یەک لا دەدەن. لە Python 3.7ـەوە هەمیشە ئەو ڕیزبەندییەی لە بیرە کە پێی زیاد کراون.
marks = {"Aram": 78, "Shilan": 91, "Karwan": 64}
for name in marks: # a dict gives its keys
print(name, end=" ")
print()
for name, mark in marks.items(): # key and value together
print(f"{name}: {mark}")
print(list(marks.keys()))
print(list(marks.values()))
print(sorted(marks))Aram Shilan Karwan Aram: 78 Shilan: 91 Karwan: 64 ['Aram', 'Shilan', 'Karwan'] [78, 91, 64] ['Aram', 'Karwan', 'Shilan']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Looping over the dictionary itself gives the keys.
بەسەر خودی دەدات.
- Lineدێڕی 5
items()gives("Aram", 78),("Shilan", 91), …, unpacked intonameandmark.items()("Aram", 78)،("Shilan", 91)، … دەدات کە بۆnameوmarkدەکرێنەوە.- Lineدێڕی 9
sorted()on a dictionary sorts its keys.sorted()لەسەر ڕیز دەکات.
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
Counting with a dictionaryژماردن بە فەرهەنگ
A dictionary is the classic tool for counting: the thing you count is the key, and the count is the value. counts.get(result, 0) + 1 reads the old count (0 the first time) and adds one. Here a football team's results are counted:
ئامرازی ناسراوی ژماردنە: ئەو شتەی دەیژمێریت و ژمارەکە . counts.get(result, 0) + 1 ژمارە کۆنەکە دەخوێنێتەوە (جاری یەکەم 0) و یەکێکی بۆ زیاد دەکات. لێرەدا ئەنجامەکانی تیپێکی تۆپی پێ دەژمێردرێن:
results = ["win", "draw", "win", "loss", "win", "draw"]
counts = {}
for result in results:
counts[result] = counts.get(result, 0) + 1
print(counts){'win': 3, 'draw': 2, 'loss': 1}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
If the key is new,
get()gives 0, so the count starts at 1. Otherwise it grows by one.ئەگەر نوێ بێت،
get()0 دەدات، بۆیە ژمارەکە لە 1ـەوە دەست پێ دەکات. ئەگەرنا یەک زیاد دەکات.
| After readingدوای خوێندنەوەی | countscounts |
|---|---|
"win" | {'win': 1} |
"draw" | {'win': 1, 'draw': 1} |
"win" | {'win': 2, 'draw': 1} |
"loss" | {'win': 2, 'draw': 1, 'loss': 1} |
"win" | {'win': 3, 'draw': 1, 'loss': 1} |
"draw" | {'win': 3, 'draw': 2, 'loss': 1} |
Dictionaries: find a value by its keyفەرهەنگەکان: نرخ بە کلیل بدۆزەرەوە
A marks bookدەفتەری نمرە
A value can be anything, even a list. Here every student (the key) has a list of marks (the value). The program adds a student, prints each average and finds the best one.
دەتوانێت هەر شتێک بێت، تەنانەت . لێرەدا هەر قوتابییەک () نمرەی هەیە (). قوتابییەک زیاد دەکات، تێکڕای هەر یەکێک چاپ دەکات و باشترینەکە دەدۆزێتەوە.
marks = {
"Aram": [78, 85, 90],
"Shilan": [91, 88, 95],
"Karwan": [64, 70, 58],
}
marks["Dilan"] = [80, 75, 85] # a new student
best_name = ""
best_average = 0
for name, student_marks in marks.items():
average = sum(student_marks) / len(student_marks)
print(f"{name:7} {average:5.1f}")
if average > best_average:
best_name = name
best_average = average
print("Best:", best_name)Aram 84.3 Shilan 91.3 Karwan 64.0 Dilan 80.0 Best: Shilan
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
A new key with a list as its value.
نوێ کە .
- Lineدێڕی 12
{name:7}and{average:5.1f}line the columns up (one decimal place).{name:7}و{average:5.1f}ستوونەکان ڕێک دەخەن (یەک ).- Lineدێڕی 13-15
Keep the best average seen so far, as in a search for the largest value.
باشترین تێکڕا کە تا ئێستا بینراوە هەڵدەگرێت، وەک گەڕان بەدوای گەورەترین .
A value can also be another dictionary. That is a nested dictionary; you read it with two pairs of brackets:
دەشتوانێت تر بێت. ئەوە ـە؛ بە دوو جووت کەوانە دەیخوێنیتەوە:
student = {
"name": "Hana",
"marks": {"maths": 90, "python": 95},
}
print(student["name"])
print(student["marks"]["python"])
student["marks"]["maths"] = 92
print(student)Hana
95
{'name': 'Hana', 'marks': {'maths': 92, 'python': 95}}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
student["marks"]is the inner dictionary;["python"]then reads from it.student["marks"]ناوەکییەکەیە؛ پاشان["python"]لێیەوە دەخوێنێتەوە.
What can be a key?چی دەتوانێت ببێتە کلیل؟
Values can be anything, but keys must be immutable: strings, numbers and tuples (of immutable things) are fine. A list cannot be a key, because it could change after it was stored. Python says the list is unhashable: it is not .
دەتوانن هەر شتێک بن، بەڵام دەبێت بن: ، ژمارەکان و (کە شتی تێدایە) گونجاون. ناتوانێت ببێتە ، چونکە دەکرێت دوای هەڵگرتنی بگۆڕێت. دەڵێت unhashableـە، واتە نییە:
seats = {(1, 2): "Aram", (3, 1): "Shilan"} # (row, column) -> name
print(seats[(1, 2)])
seats[(2, 2)] = "Karwan"
print(len(seats))
bad = {[1, 2]: "Rezan"}Aram
3
Traceback (most recent call last):
File "seat_keys.py", line 5, in <module>
bad = {[1, 2]: "Rezan"}
^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Each key is a
(row, column)tuple: a classroom seating plan.هەر
(row, column)ـە: نەخشەی دانیشتنی پۆلێک.- Lineدێڕی 5
A list as a key:
TypeError: unhashable type: 'list'.وەک :
TypeError: unhashable type: 'list'.
How a dictionary differs from a list, and the rules for keys and values: which values can be keys and why.
چ جیاوازییەکی لەگەڵ هەیە و یاساکانی و : کام دەتوانێت ببێتە و بۆچی.
Watch 2:20–6:08: dictionaries compared with lists, then the key and value rules.
لە 2:20 تا 6:08 سەیر بکە: بەراوردی لەگەڵ ، پاشان یاساکانی و .
Which one should I use?کامیان بەکار بهێنم؟
All four structures hold many values. The questions that decide are: Does the order matter? Will it change? Are duplicates allowed? Do I find things by position or by name? (A data structure is exactly this: a way to keep values together with the operations on them. What is a data structure? adds two more, the stack and the queue.)
هەر چوار چەندین هەڵدەگرن. ئەو پرسیارانەی بڕیار دەدەن ئەمانەن: ئایا ڕیزبەندی گرنگە؟ دەگۆڕێت؟ دووبارە ڕێگەپێدراوە؟ شتەکان بە شوێن دەدۆزمەوە یان بە ناو؟ ( ڕێک ئەمەیە: ڕێگایەک بۆ پێکەوە هەڵگرتنی لەگەڵ ئەو کارانەی لەسەریان دەکرێن. پێکهاتەی دراوە چییە؟ دوو دانەی تر زیاد دەکات: و .)
| Questionپرسیار | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Written asشێوەی نووسین | [1, 2, 2] | (1, 2, 2) | {1, 2} | {"a": 1} |
| Keeps orderڕیزبەندی دەپارێزێت | yesبەڵێ | yesبەڵێ | noنەخێر | yes (insertion order)بەڵێ (ڕیزی زیادکردن) |
| Can changeدەگۆڕدرێت | yesبەڵێ | noنەخێر | yesبەڵێ | yesبەڵێ |
| Duplicatesدووبارە | allowedڕێگەپێدراو | allowedڕێگەپێدراو | neverهەرگیز | keys never; values allowed هەرگیز؛ ڕێگەپێدراو |
| Find an item by بە چی دەدۆزرێتەوە | index x[0] x[0] | index x[0] x[0] | only inتەنها in | key d["a"] d["a"] |
| Good forباشە بۆ | a row of values that growsڕیزێک کە گەورە دەبێت | a fixed recordتۆمارێکی جێگیر | unique values, fast in, set maths بێ دووبارە، inـی خێرا، بیرکاریی | looking things up, countingگەڕان بەدوای شتدا، ژماردن |
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
{} for an empty set{} بۆ بەتاڵ | You get an empty dictionary. بەتاڵ وەردەگریت. | set() |
(5) for a one-item tuple(5) بۆ بە یەک | It is just the number 5.تەنها ژمارە 5ـە. | (5,) |
Changing a tuple: t[0] = 1گۆڕینی : t[0] = 1 | TypeErrorTypeError | Build a new tuple, or use a list. نوێ دروست بکە، یان بەکار بهێنە. |
d[key] for a key that may be missingd[key] بۆ کە لەوانەیە نەبێت | KeyErrorKeyError | if key in d: or d.get(key, default)if key in d: یان d.get(key, default) |
s[0] on a sets[0] لەسەر | TypeError: a set has no positions.TypeError: شوێنی نییە. | sorted(s)[0], or use a listsorted(s)[0]، یان بەکار بهێنە |
500 in prices to look for a value500 in prices بۆ گەڕان بەدوای | Always False: in checks keys.هەمیشە False: in دەپشکنێت. | 500 in prices.values() |
| A list as a key وەک | TypeError: unhashable type: 'list'TypeError: unhashable type: 'list' | Use a tuple. بەکار بهێنە. |
| Unpacking with the wrong number of namesکردنەوە بە ژمارەی هەڵەی ناو | ValueErrorValueError | One name per value.یەک ناو بۆ هەر . |
Deleting keys inside for key in d:سڕینەوەی لەناو for key in d: | RuntimeError: dictionary changed size during iterationRuntimeError: dictionary changed size during iteration | Loop over list(d), a copy of the keys. بەسەر list(d)ـدا بکە، کۆپییەکی . |
Common mistakesهەڵە باوەکان
Do not change a dictionary while looping over itلە کاتی خولدا فەرهەنگ مەگۆڕە
The last row of the table needs a picture in code. Removing cheap items while looping over the same dictionary stops the program:
دوایین ڕیزی خشتەکە پێویستی بە نموونەیەکی کۆدە. لابردنی کاڵا هەرزانەکان لە کاتی بەسەر هەمان دەوەستێنێت:
prices = {"tea": 500, "bread": 250, "salt": 200}
for item in prices:
if prices[item] < 300:
del prices[item]Traceback (most recent call last):
File "loop_delete.py", line 2, in <module>
for item in prices:
^^^^^^
RuntimeError: dictionary changed size during iterationprices = {"tea": 500, "bread": 250, "salt": 200}
for item in list(prices): # loop over a copy of the keys
if prices[item] < 300:
del prices[item]
print(prices){'tea': 500}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
list(prices)is a separate list of the keys, so changing the dictionary is safe.list(prices)جیای ، بۆیە گۆڕینی سەلامەتە.
Exercises: tuples and setsڕاهێنانەکان: تاپڵەکان و کۆمەڵەکان
Unpack the tuple (23, 10, 2026) into day, month and year. Print the date as 23/10/2026 and as 2026-10-23.
(23, 10, 2026) بکەرەوە بۆ day، month و year. بەروارەکە وەک 23/10/2026 و وەک 2026-10-23 چاپ بکە.
Show answerوەڵامەکە پیشان بدە
date = (23, 10, 2026)
day, month, year = date
print(f"{day}/{month}/{year}")
print(f"{year}-{month}-{day}")23/10/2026 2026-10-23
Without running it, write what this program prints. Then explain the last line.
بەبێ جێبەجێکردن، بنووسە ئەم چی چاپ دەکات. پاشان دوایین دێڕ ڕوون بکەرەوە.
x = 7
y = x + 3
x = 1
print(x, y)
x, y = y, x * 2
print(x, y)
print(z)Show answerوەڵامەکە پیشان بدە
x = 7
y = x + 3
x = 1
print(x, y)
x, y = y, x * 2
print(x, y)
print(z)1 10
10 2
Traceback (most recent call last):
File "ex_simultaneous.py", line 7, in <module>
print(z)
^
NameError: name 'z' is not definedLines 1–3 run one after another, so y keeps the 10 it got before x became 1. In line 5 Python first works out the whole right side with the old values, (10, 2), and only then assigns: x gets 10 and y gets 2. Line 7 uses z, which never got a value, so Python raises NameError.
دێڕەکانی 1–3 یەک لە دوای یەک جێبەجێ دەبن، بۆیە y ئەو 10ـەی دەمێنێت کە پێش ئەوەی x ببێتە 1 وەریگرتبوو. لە دێڕی 5دا سەرەتا هەموو لای ڕاست بە کۆنەکان هەژمار دەکات ((10, 2)) و تەنها پاشان دایاندەنێت: x 10 وەردەگرێت و y 2. دێڕی 7 z بەکار دەهێنێت کە هەرگیز وەرنەگرتووە، بۆیە NameError دروست دەکات.
Without running it, write what this program prints.
بەبێ جێبەجێکردن، بنووسە ئەم چی چاپ دەکات.
t = (45, 12, 45, 30)
print(t.index(45), t.count(45))
u = t + (5,)
print(len(u), max(u), min(u), sum(u))
print(sorted(t))
print(t)Show answerوەڵامەکە پیشان بدە
t = (45, 12, 45, 30)
print(t.index(45), t.count(45))
u = t + (5,)
print(len(u), max(u), min(u), sum(u))
print(sorted(t))
print(t)0 2 5 45 5 137 [12, 30, 45, 45] (45, 12, 45, 30)
index(45) finds the first 45, at index 0, and count(45) finds two of them. u has five items and their sum is . sorted(t) returns a list, while t itself stays as it was.
index(45) یەکەم 45 دەدۆزێتەوە کە لەسەر 0ـە و count(45) دوو دانەیان دەدۆزێتەوە. u پێنج هەیە و کۆکەیان ـە. sorted(t) دەگەڕێنێتەوە، لە کاتێکدا t خۆی وەک خۆی دەمێنێتەوە.
Keep the results ("Aram", 78), ("Shilan", 91) and ("Karwan", 64) in a tuple of tuples, because they must not change. Print them as a numbered table with the columns lined up.
ئەنجامەکانی ("Aram", 78)، ("Shilan", 91) و ("Karwan", 64) لە هەڵبگرە، چونکە نابێت بگۆڕێن. وەک خشتەیەکی ژمارەکراو چاپیان بکە کە ستوونەکانی ڕێک بن.
Hintئاماژە
enumerate(results, start=1) counts from 1; :<8 and :>5 line the columns up.
enumerate(results, start=1) لە 1ـەوە دەژمێرێت؛ :<8 و :>5 ستوونەکان ڕێک دەخەن.
Show answerوەڵامەکە پیشان بدە
results = (("Aram", 78), ("Shilan", 91), ("Karwan", 64))
print(f"{'No.':<5}{'Name':<8}{'Mark':>5}")
for number, (name, mark) in enumerate(results, start=1):
print(f"{number:<5}{name:<8}{mark:>5}")No. Name Mark 1 Aram 78 2 Shilan 91 3 Karwan 64
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Each record is a tuple, and the whole table is a tuple too.
هەر تۆمارێک و هەموو خشتەکەش .
- Lineدێڕی 3
enumerate()gives the numbers;(name, mark)unpacks each record inside the loop header.enumerate()ژمارەکان دەدات؛(name, mark)هەر تۆمارێک لە سەری دەکاتەوە.
Ask how many e-mail addresses the user has, read them into a tuple, then build two tuples: the user names (the part before @) and the domain names (the part after it).
بپرسە چەند هەیە، بیانخوێنەوە بۆ ناو ، پاشان دوو دروست بکە: (بەشی پێش @) و (بەشی دوای @).
Hintئاماژە
address.split("@") returns a list of two strings that you can unpack.
address.split("@") دوو دەگەڕێنێتەوە کە دەتوانیت بیکەیتەوە.
Show answerوەڵامەکە پیشان بدە
count = int(input("How many e-mail addresses? "))
addresses = ()
for i in range(count):
addresses += (input("E-mail: ").strip(),)
names = ()
domains = ()
for address in addresses:
name, domain = address.split("@")
names += (name,)
domains += (domain,)
print(names)
print(domains)How many e-mail addresses? 2
E-mail: aram@example.com
E-mail: shilan.k@school.example.org
('aram', 'shilan.k')
('example.com', 'school.example.org')Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
+= (… ,)adds one item by building a new tuple each time.+= (… ,)بە دروستکردنی نوێ لە هەر جارێکدا یەک زیاد دەکات.- Lineدێڕی 9
split("@")gives two parts, unpacked intonameanddomain.split("@")دوو بەش دەدات کە بۆnameوdomainدەکرێنەوە.
An address without @, or with two of them, would stop the unpacking with ValueError, the same error as in A function can return a tuple. A real program would check the address first.
بەبێ @، یان بە دوو دانە، کردنەوەکە بە ValueError دەوەستێنێت، هەمان کردار دەتوانێت تاپڵێک بگەڕێنێتەوە. ڕاستەقینە سەرەتا دەپشکنێت.
set() removes duplicates but loses the order. Write a loop that keeps the first appearance of every name, in the original order, for ["Aram", "Shilan", "Aram", "Karwan", "Shilan", "Dilan"].
set() دووبارەکان لادەبات بەڵام ڕیزبەندی لەدەست دەدات. بنووسە کە یەکەم دەرکەوتنی هەر ناوێک بە ڕیزبەندیی سەرەتایی بپارێزێت، بۆ ["Aram", "Shilan", "Aram", "Karwan", "Shilan", "Dilan"].
Hintئاماژە
Keep a set called seen and a list called unique.
بە ناوی seen و بە ناوی unique بەکار بهێنە.
Show answerوەڵامەکە پیشان بدە
names = ["Aram", "Shilan", "Aram", "Karwan", "Shilan", "Dilan"]
seen = set()
unique = []
for name in names:
if name not in seen:
seen.add(name)
unique.append(name)
print(unique)
print(list(dict.fromkeys(names)))['Aram', 'Shilan', 'Karwan', 'Dilan'] ['Aram', 'Shilan', 'Karwan', 'Dilan']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-8
A set remembers what was seen (fast
in); a list keeps the order.ئەوەی بینراوە لە بیر دەگرێت (
inـی خێرا)؛ ڕیزبەندییەکە دەپارێزێت.- Lineدێڕی 9
A short extra: dictionary keys are unique and keep insertion order, so
dict.fromkeys()does the same in one line.زیادەیەکی کورت: دووبارە نابنەوە و ڕیزی زیادکردن دەپارێزن، بۆیە
dict.fromkeys()هەمان کار لە یەک دێڕدا دەکات.
morning = {"Aram", "Shilan", "Karwan", "Lana"} and evening = {"Karwan", "Soran", "Lana", "Hana", "Rezan"}. Print who attends both, who attends only the morning class, and how many different students there are.
morning = {"Aram", "Shilan", "Karwan", "Lana"} و evening = {"Karwan", "Soran", "Lana", "Hana", "Rezan"}. چاپ بکە کێ لە هەردووکیاندایە، کێ تەنها لە پۆلی بەیانیدایە و چەند قوتابیی جیاواز هەیە.
Show answerوەڵامەکە پیشان بدە
morning = {"Aram", "Shilan", "Karwan", "Lana"}
evening = {"Karwan", "Soran", "Lana", "Hana", "Rezan"}
print("Both:", sorted(morning & evening))
print("Only morning:", sorted(morning - evening))
print("Different students:", len(morning | evening))Both: ['Karwan', 'Lana'] Only morning: ['Aram', 'Shilan'] Different students: 7
Check: names, but Karwan and Lana are counted twice, so different students.
پشکنین: ناو، بەڵام Karwan و Lana دوو جار ژمێردراون، بۆیە قوتابیی جیاواز.
Exercises: tuples and setsڕاهێنانەکان: تاپڵەکان و کۆمەڵەکان
Exercises: dictionariesڕاهێنانەکان: فەرهەنگەکان
Read a word and print how many times each letter appears, in the order the letters first appear.
وشەیەک بخوێنەوە و چاپ بکە هەر پیتێک چەند جار دەردەکەوێت، بە ئەو ڕیزبەندییەی کە پیتەکان یەکەم جار دەردەکەون.
Show answerوەڵامەکە پیشان بدە
word = input("A word: ")
counts = {}
for letter in word:
counts[letter] = counts.get(letter, 0) + 1
for letter, count in counts.items():
print(letter, count)A word: banana b 1 a 3 n 2
Store four everyday words with their Kurdish meaning in a dictionary. Ask for English words until the user types quit. Ignore extra spaces and capital letters, and answer I don't know that word yet. for unknown words.
چوار وشەی ڕۆژانە لەگەڵ واتا کوردییەکەیان لە هەڵبگرە. داوای وشەی ئینگلیزی بکە تا quit دەنووسێت. زیادە و پیتی گەورە پشتگوێ بخە و بۆ وشەی نەناسراو وەڵامی I don't know that word yet. بدەرەوە.
Show answerوەڵامەکە پیشان بدە
words = {"tea": "چا", "bread": "نان", "water": "ئاو", "book": "کتێب"}
while True:
word = input("English word (or quit): ").strip().lower()
if word == "quit":
break
print(words.get(word, "I don't know that word yet."))English word (or quit): tea چا English word (or quit): Water ئاو English word (or quit): milk I don't know that word yet. English word (or quit): quit
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
.strip().lower()turns" Water"into"water"..strip().lower()" Water"دەکات بە"water".- Lineدێڕی 6
get()with a default answers unknown words without aKeyError.get()لەگەڵ وەڵامی وشەی نەناسراو دەداتەوە بەبێKeyError.
marks = {"Aram": [78, 85], "Shilan": [91, 88], "Karwan": [64, 70]}. Add the mark 90 to Aram's list, then print every student's highest mark.
marks = {"Aram": [78, 85], "Shilan": [91, 88], "Karwan": [64, 70]}. نمرەی 90 بۆ لیستەکەی Aram زیاد بکە، پاشان بەرزترین نمرەی هەموو قوتابییەک چاپ بکە.
Show answerوەڵامەکە پیشان بدە
marks = {"Aram": [78, 85], "Shilan": [91, 88], "Karwan": [64, 70]}
marks["Aram"].append(90) # a new mark for Aram
for name, student_marks in marks.items():
print(name, max(student_marks))Aram 90 Shilan 91 Karwan 70
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
marks["Aram"]is a list, soappend()changes it inside the dictionary.marks["Aram"]، بۆیەappend()لەناو دەیگۆڕێت.
Without running it, write what this program prints.
بەبێ جێبەجێکردن، بنووسە ئەم چی چاپ دەکات.
a = (1, 2, 3)
b = {3, 2, 1, 2}
c = {"x": 1, "y": 2}
c["x"] = 10
print(len(a), len(b), len(c))
print(a[1], 2 in b, "y" in c, 2 in c)
print(c)Show answerوەڵامەکە پیشان بدە
a = (1, 2, 3)
b = {3, 2, 1, 2}
c = {"x": 1, "y": 2}
c["x"] = 10
print(len(a), len(b), len(c))
print(a[1], 2 in b, "y" in c, 2 in c)
print(c)3 3 2
2 True True False
{'x': 10, 'y': 2}b keeps 1, 2 and 3 once, so its length is 3. c["x"] = 10 replaces a value; the dictionary still has two pairs. 2 in c is False because 2 is a value, not a key.
b 1، 2 و 3 هەر یەکە یەک جار دەهێڵێتەوە، بۆیە درێژییەکەی 3ـە. c["x"] = 10 دەگۆڕێت؛ هێشتا دوو جووتی هەیە. 2 in c Falseـە چونکە 2 نەک .
Read a whole number as text and say it digit by digit in words: 2026 becomes two zero two six. Use a dictionary from each digit character to its word. (You may store Kurdish words instead.)
وەک دەق بخوێنەوە و بە بە وشە بیڵێ: 2026 دەبێتە two zero two six. بەکار بهێنە کە هەر دەبات بۆ وشەکەی. (دەتوانیت وشە کوردییەکان هەڵبگریت: سفر، یەک، دوو…)
Show answerوەڵامەکە پیشان بدە
words = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four",
"5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"}
number = input("A whole number: ").strip()
result = []
for digit in number:
result.append(words.get(digit, "?"))
print(" ".join(result))A whole number: 2026 two zero two six
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-2
The keys are the characters
"0"to"9", becauseinput()gives text."0"تا"9"ـن، چونکەinput()دەق دەدات.- Lineدێڕی 6
get(digit, "?")answers?for anything that is not a digit.get(digit, "?")بۆ هەر شتێک کە نەبێت?دەداتەوە.
Read some students into a dictionary: the key is the student number, the value is a tuple (name, percentage) that must not change. Then show all records, search for one number, and print the top student.
چەند قوتابییەک بخوێنەوە بۆ ناو : ژمارەی قوتابییە و (name, percentage)ـە کە نابێت بگۆڕێت. پاشان هەموو تۆمارەکان پیشان بدە، بەدوای ژمارەیەکدا بگەڕێ و باشترین قوتابی چاپ بکە.
Show answerوەڵامەکە پیشان بدە
records = {} # student number -> (name, percentage)
count = int(input("How many students? "))
for i in range(count):
number = int(input("Student number: "))
name = input("Name: ")
percent = float(input("Percentage: "))
records[number] = (name, percent)
for number, (name, percent) in records.items():
print(number, name, percent)
wanted = int(input("Search for student number: "))
if wanted in records:
name, percent = records[wanted]
print("Found:", name, percent)
else:
print("No student has number", wanted)
best_number = None
for number in records:
if best_number is None or records[number][1] > records[best_number][1]:
best_number = number
print("Top student:", records[best_number][0])How many students? 3 Student number: 1001 Name: Aram Percentage: 78.5 Student number: 1002 Name: Shilan Percentage: 91 Student number: 1003 Name: Karwan Percentage: 64.5 1001 Aram 78.5 1002 Shilan 91.0 1003 Karwan 64.5 Search for student number: 1004 No student has number 1004 Top student: Shilan
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7
A tuple as the value: the record cannot be changed by mistake.
وەک : تۆمارەکە بە هەڵە ناگۆڕدرێت.
- Lineدێڕی 9
items()gives(number, (name, percent)); both levels are unpacked at once.items()(number, (name, percent))دەدات؛ هەردوو ئاستەکە پێکەوە دەکرێنەوە.- Lineدێڕی 19-22
Keep the number of the best percentage seen so far.
ژمارەی باشترین ڕێژە کە تا ئێستا بینراوە هەڵبگرە.
Keep {"Shilan": 104, "Aram": 101, "Karwan": 117} (name → room extension) and repeat a menu until the user types 0: show all, add a person, delete a person, change a number, look a person up, and show everyone sorted by name.
{"Shilan": 104, "Aram": 101, "Karwan": 117} هەڵبگرە (ناو ← ژمارەی ناوخۆیی ژوور) و مێنیوێک دووبارە بکەرەوە تا 0 دەنووسێت: هەموو پیشان بدە، کەسێک زیاد بکە، کەسێک بسڕەوە، ژمارەیەک بگۆڕە، بەدوای کەسێکدا بگەڕێ و هەمووان بە ڕیزی ناو پیشان بدە.
Hintئاماژە
A while True: loop with if/elif for each choice; break on 0.
while True: بە if/elif بۆ هەر هەڵبژاردەیەک؛ لەسەر 0 break.
Show answerوەڵامەکە پیشان بدە
book = {"Shilan": 104, "Aram": 101, "Karwan": 117} # name -> room extension
while True:
print("1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit")
choice = input("Choice: ").strip()
if choice == "0":
break
elif choice == "1":
for name, number in book.items():
print(name, number)
elif choice == "2":
name = input("Name: ").strip()
book[name] = int(input("Extension: "))
elif choice == "3":
name = input("Name: ").strip()
if book.pop(name, None) is None:
print(name, "is not in the book.")
elif choice == "4":
name = input("Name: ").strip()
if name in book:
book[name] = int(input("New extension: "))
else:
print(name, "is not in the book.")
elif choice == "5":
name = input("Name: ").strip()
print(name, book.get(name, "is not in the book."))
elif choice == "6":
for name in sorted(book):
print(name, book[name])
else:
print("Please type a number from 0 to 6.")1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 1 Shilan 104 Aram 101 Karwan 117 1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 2 Name: Dilan Extension: 122 1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 4 Name: Aram New extension: 109 1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 3 Name: Rezan Rezan is not in the book. 1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 5 Name: Karwan Karwan 117 1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 6 Aram 109 Dilan 122 Karwan 117 Shilan 104 1 Show all 2 Add 3 Delete 4 Change 5 Look up 6 Sorted 0 Quit Choice: 0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 16
pop(name, None)givesNoneinstead of aKeyErrorwhen the name is missing.pop(name, None)کاتێک ناوەکە نییە لەبریKeyErrorNoneدەدات.- Lineدێڕی 28-29
sorted(book)sorts the keys; the dictionary itself keeps its own order.sorted(book)ڕیز دەکات؛ خۆی ڕیزی خۆی دەپارێزێت.
Choice 1 shows the pairs in the order they were added; choice 6 shows them by name. A typing mistake in an extension would crash int(): the next lesson's get_int() (A safe input function) fixes that.
هەڵبژاردەی 1 جووتەکان بە ئەو ڕیزەی زیاد کراون پیشان دەدات؛ هەڵبژاردەی 6 بە ڕیزی ناو. هەڵەیەکی نووسین لە ژمارەی ناوخۆییدا int() دەخات: get_int()ـی وانەی داهاتوو (کردارێکی نێوخستەی سەلامەت) چاکی دەکات.
Exercises: tuples and setsڕاهێنانەکان: تاپڵەکان و کۆمەڵەکان
Challenge: a catalogue of placesڕاهێنانی قورستر: کاتالۆگی شوێنەکان
Build a catalogue of places in Kurdistan as a dictionary of dictionaries: the key is the place's name, the value holds its city, region and kind. Start with the Erbil Citadel, a UNESCO World Heritage Site since 2014. Write functions that list all places, find a place by name, find the places of a region, and (for the person who manages the catalogue) add, change and delete a place. Then put them behind a menu like the phone book's.
کاتالۆگێکی شوێنەکانی کوردستان وەک لە دروست بکە: ناوی شوێنەکەیە و شار، هەرێم و جۆرەکەی هەڵدەگرێت. بە قەڵای هەولێر دەست پێ بکە، کە لە 2014ـەوە شوێنێکی میراتی جیهانیی UNESCOـیە. بنووسە بۆ پیشاندانی هەموو شوێنەکان، دۆزینەوەی شوێنێک بە ناو، دۆزینەوەی شوێنەکانی هەرێمێک و (بۆ ئەو کەسەی کاتالۆگەکە بەڕێوە دەبات) زیادکردن، گۆڕین و سڕینەوەی شوێنێک. پاشان وەک دەفتەری تەلەفۆنەکە بیانخەرە پشت مێنیوێکەوە.
Hintئاماژە
places[name]["region"] reads the region of one place; loop over places.items() to search.
places[name]["region"] هەرێمی شوێنێک دەخوێنێتەوە؛ بۆ گەڕان بەسەر places.items()ـدا بکە.
Show answerوەڵامەکە پیشان بدە
places = {
"Erbil Citadel": {"city": "Erbil", "region": "Erbil", "kind": "citadel"},
"Delal Bridge": {"city": "Zakho", "region": "Duhok", "kind": "stone bridge"},
"Amna Suraka": {"city": "Sulaymaniyah", "region": "Sulaymaniyah", "kind": "museum"},
}
def show_all():
for name, info in sorted(places.items()):
print(f"{name}: {info['kind']} in {info['city']}")
def find_by_name(name):
info = places.get(name)
if info is None:
print("No place called", name)
else:
print(name, info)
def find_by_region(region):
found = []
for name, info in places.items():
if info["region"] == region:
found.append(name)
print(region + ":", found if found else "nothing yet")
def add_or_change(name, city, region, kind): # admin only
places[name] = {"city": city, "region": region, "kind": kind}
def delete(name): # admin only
places.pop(name, None)
places["Erbil Citadel"]["unesco"] = 2014 # one more detail
show_all()
find_by_name("Erbil Citadel")
find_by_region("Duhok")
add_or_change("Gali Ali Beg", "Rawanduz", "Erbil", "waterfall")
find_by_region("Erbil")
delete("Gali Ali Beg")
find_by_region("Halabja")Amna Suraka: museum in Sulaymaniyah
Delal Bridge: stone bridge in Zakho
Erbil Citadel: citadel in Erbil
Erbil Citadel {'city': 'Erbil', 'region': 'Erbil', 'kind': 'citadel', 'unesco': 2014}
Duhok: ['Delal Bridge']
Erbil: ['Erbil Citadel', 'Gali Ali Beg']
Halabja: nothing yetExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-5
A nested dictionary: every value is itself a dictionary.
: هەر خۆی .
- Lineدێڕی 37
Adding a key to an inner dictionary.
زیادکردنی بۆ ناوەکییەکە.
The menu is left to you: copy the loop of the phone book and call one function for each choice.
مێنیوەکە بۆ خۆتە: دەفتەری تەلەفۆنەکە کۆپی بکە و بۆ هەر هەڵبژاردەیەک بانگ بکە.
Summaryپوختە
- A tuple
(a, b)is an ordered, unchangeable group; the commas make it ((5,)).+,*and slices build new tuples; its only methods arecount()andindex(). - Packing and unpacking:
x, y = point,a, b = b, a, and functions that return several values. - A set
{…}has no order and no duplicates;inis fast;|,&,-,^and<=do set maths. Empty set:set(). - A dictionary
{key: value}finds values by key.d[key] = vadds or replaces,get()avoidsKeyError,items()loops over pairs,update()merges another dictionary. - Keys (and set items) must be immutable: strings, numbers, tuples. Values can be anything, even lists and dictionaries.
-
(a, b)کۆمەڵێکی ڕیزبەند و نەگۆڕە؛ کۆماکان دروستی دەکەن ((5,)).+،*و نوێ دروست دەکەن؛ تەنهاcount()وindex()ـن. - پێچانەوە و کردنەوە:
x, y = point،a, b = b, aو کە چەند دەگەڕێننەوە. -
{…}نە ڕیزی هەیە و نە دووبارە؛inخێرایە؛|،&،-،^و<=بیرکاریی دەکەن. بەتاڵ:set(). -
{key: value}بە دەدۆزێتەوە.d[key] = vزیاد دەکات یان دەگۆڕێت،get()ڕێگری لەKeyErrorدەکات،items()بەسەر جووتەکاندا دەکات،update()تر تێکەڵ دەکات. - (و ) دەبێت بن: ، ژمارەکان، . دەتوانن هەر شتێک بن، تەنانەت و .
What is the difference between [1, 2] and (1, 2)?جیاوازیی نێوان [1, 2] و (1, 2) چییە؟
The first is a list and can change; the second is a tuple and cannot. A tuple can also be a dictionary key.
یەکەمیان و دەگۆڕدرێت؛ دووەمیان و ناگۆڕدرێت. دەشتوانێت ببێتە .
How do you count how many different values a list has?چۆن دەژمێریت لیستێک چەند نرخێکی جیاوازی هەیە؟
len(set(the_list)): the set drops the duplicates.
len(set(the_list)): دووبارەکان فڕێ دەدات.
What are three safe ways to read a key that might be missing?سێ ڕێگای سەلامەت بۆ خوێندنەوەی کلیلێک کە لەوانەیە نەبێت چین؟
Check with in first, use get() with a default, or catch KeyError with try/except.
سەرەتا بە in بپشکنە، get() لەگەڵ بەکار بهێنە، یان KeyError بە try/except بگرە.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
Lists, tuples and sets side by side: how each is written, which keep order, which allow duplicates and which can change.
، و لە تەنیشت یەکەوە: هەر یەکێکیان چۆن دەنووسرێت، کامیان ڕیزبەندی دەپارێزن، کامیان ڕێگە بە دووبارە دەدەن و کامیان دەگۆڕدرێن.
A 6-minute comparison of lists, tuples and sets (syntax 0:15, sets 0:52, lists vs tuples 2:19, summary table 4:27). Dictionaries are not in this video.
بەراوردێکی 6 خولەکیی ، و ( 0:15، 0:52، بەرامبەر 2:19، خشتەی کورتە 4:27). لەم ڤیدیۆیەدا نین.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Handling Errors with try and exceptمامەڵەکردن لەگەڵ هەڵاوێردە بە try و except
Related lecturesوانە پەیوەندیدارەکان
- Return Values and Noneنرخە گەڕاوەکان و None
- Handling Errors with try and exceptمامەڵەکردن لەگەڵ هەڵاوێردە بە try و except
- Project: Binary to Decimal Converterپڕۆژیلە: گۆڕینی دووانی بۆ دەیی
- Union, Intersection, Difference and Complementیەکگرتن، یەکتربڕین، جیاوازیی کۆمەڵە و تەواوکەر
- The Python You Need for the AI Labsئەو Pythonـەی بۆ تاقیگەکانی ژیریی دەستکرد پێویستە
- Arrays in PHPڕیزەکەکان لە PHPـدا
- Stacks: Last In, First Outستاکەکان: دوایین هاتوو، یەکەم دەرچوو
- Binary Search and Hashingگەڕانی دووانی و هاشکردن
- Variables and Data Typesگۆڕاوەکان و جۆرەکانی دراوە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python Tutorial 5: Data Structures (5.3 Tuples and sequences, 5.4 Sets, 5.5 Dictionaries, 5.6 Looping techniques)
- Python Library: Built-in types (tuple, set and frozenset, dict)
- CS50's Introduction to Programming with Python, lecture 2 notes (dictionaries)
- Liang, Introduction to Programming Using Python: table of contents (chapter 14, Tuples, Sets, and Dictionaries)
- Wikipedia: Erbil Citadel (UNESCO World Heritage Site, inscribed 2014)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.