נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
8
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

מילונים, טאפלים וסטיםDicts, tuples & sets

מפתח-ערך, טאפלים בלתי משתנים, סטים בלי כפילויות.

Key-value pairs, immutable tuples, sets without duplicates.

01מילונים: מפתח וערךDictionaries: key and value

מילון שומר זוגות של מפתח וערך. במקום לזכור ש"אינדקס 2 הוא מספר העמודים", נותנים לכל שדה שם. ככה ספר אחד בפרויקט שלנו נהיה מילון אחד.

A dictionary (dict) stores pairs of key and value. Instead of remembering that "index 2 is the page count", each field gets a name. That way one book in our project becomes one dict.

dict.py
book = {"title": "Dune", "author": "Frank Herbert", "pages": 412}
print(book["title"])
book["rating"] = 5
book["pages"] = 896
print(book)
print(len(book), "author" in book)
פלטOutput
Dune
{'title': 'Dune', 'author': 'Frank Herbert', 'pages': 896, 'rating': 5}
4 True
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

מילון הוא כמו ספר טלפונים: מחפשים לפי שם (המפתח) ומקבלים מספר (הערך). אף אחד לא מחפש "את השורה ה-37".

A dict is like a phone book: you look up a name (the key) and get a number (the value). Nobody looks up "line 37".

טעות נפוצהCommon mistake

קוראים מפתח שלא קיים.

Reading a key that doesn't exist.

dict.py
book = {"title": "Dune"}
print(book["rating"])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/dict.py", line 2, in <module>
    print(book["rating"])
          ~~~~^^^^^^^^^^
KeyError: 'rating'
בעברית פשוטה: In plain words: KeyError: 'rating': בודקים עם in, או book.get("rating") שמחזירה None, או book.get("rating", 0) עם ברירת מחדל.KeyError: 'rating': check with in, or use book.get("rating") (returns None) or book.get("rating", 0) with a default.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

מילון מחבר מפתח לערך, כמו מילה להסבר שלה.

A dict links a key to a value, like a word to its meaning.

עוד דוגמה: מילון חיותOne more: an animal dictionary
example.py
legs = {"cat": 4, "bird": 2}
legs["spider"] = 8
print(legs["bird"])
print(legs.get("fish", 0))
for animal, n in legs.items():
    print(animal, n)
פלטOutput
2
0
cat 4
bird 2
spider 8
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02לעבור על מילוןLooping over a dict

לולאה על מילון נותנת את המפתחות. .items() נותנת זוגות (מפתח, ערך), ו-.values() רק ערכים. דפוס שימושי במיוחד: ספירה עם counts[x] = counts.get(x, 0) + 1.

Looping over a dict gives the keys. .items() gives (key, value) pairs, and .values() just values. A very useful pattern: counting with counts[x] = counts.get(x, 0) + 1.

dloop.py
ratings = {"Dune": 5, "Emma": 4, "Ulysses": 3}
for title, stars in ratings.items():
    print(f"{title}: {'⭐' * stars}")
genres = ["sci-fi", "kids", "sci-fi", "classic", "sci-fi"]
counts = {}
for g in genres:
    counts[g] = counts.get(g, 0) + 1
print(counts)
פלטOutput
Dune: ⭐⭐⭐⭐⭐
Emma: ⭐⭐⭐⭐
Ulysses: ⭐⭐⭐
{'sci-fi': 3, 'kids': 1, 'classic': 1}
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

.get(x, 0) הוא כמו לשאול "כמה כבר יש לנו מזה? אם עוד אין בכלל, תניח אפס".

.get(x, 0) is like asking "how many of these do we have? If none yet, assume zero".

טעות נפוצהCommon mistake

משנים את גודל המילון בזמן לולאה עליו.

Changing a dict's size while looping over it.

dloop.py
stock = {"Dune": 0, "Emma": 2}
for title in stock:
    if stock[title] == 0:
        del stock[title]
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/dloop.py", line 2, in <module>
    for title in stock:
                 ^^^^^
RuntimeError: dictionary changed size during iteration
בעברית פשוטה: In plain words: RuntimeError: dictionary changed size during iteration: עוברים על עותק: for title in list(stock):.RuntimeError: dictionary changed size during iteration: loop over a copy: for title in list(stock):.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03רשימה של מילוניםA list of dicts

רוב הנתונים האמיתיים בנויים כרשימה של מילונים: כל פריט הוא מילון עם אותם שדות. ככה תיראה הספרייה שלנו, וככה נראה JSON שמגיע מאתרים (מפגש 21).

Most real data is a list of dicts: each item is a dict with the same fields. Our library will look like this, and so does JSON from websites (session 21).

nested.py
shelf = [
    {"title": "Dune", "pages": 412, "read": True},
    {"title": "Emma", "pages": 474, "read": False},
]
shelf.append({"title": "Matilda", "pages": 240, "read": True})
for b in shelf:
    mark = "✓" if b["read"] else " "
    print(f"[{mark}] {b['title']} ({b['pages']})")
total = sum(b["pages"] for b in shelf if b["read"])
print(total)
פלטOutput
[✓] Dune (412)
[ ] Emma (474)
[✓] Matilda (240)
652
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

ויזואלייזר זיכרוןMemory visualizerרשימה שמצביעה על מילוניםA list pointing at dicts

מה קורה עכשיוWhat happens now

פלטOutput

משתנים (frames)Variables (frames)

אובייקטים בזיכרוןObjects in memory

אנלוגיה מהחייםReal-life analogy

רשימה של מילונים היא כמו קלסר כרטיסים: הקלסר הוא הרשימה, וכל כרטיס הוא מילון עם אותם שדות מודפסים.

A list of dicts is like a card file: the box is the list and each card is a dict with the same printed fields.

טעות נפוצהCommon mistake

מנסים לגשת למילון ברשימה לפי מפתח בלי לבחור קודם פריט.

Accessing a key on the list itself instead of on one item.

nested.py
shelf = [{"title": "Dune"}]
print(shelf["title"])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/nested.py", line 2, in <module>
    print(shelf["title"])
          ~~~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not str
בעברית פשוטה: In plain words: TypeError: list indices must be integers or slices, not str: קודם פריט, אחר כך מפתח: shelf[0]["title"].TypeError: list indices must be integers or slices, not str: item first, then key: shelf[0]["title"].
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04טאפלים ופירוקTuples and unpacking

טאפל הוא כמו רשימה שאי אפשר לשנות. משתמשים בו לנתונים שהולכים יחד ולא אמורים להשתנות, כמו קואורדינטות. פירוק מחלק טאפל לכמה משתנים בשורה אחת.

A tuple is like a list that can't change. Use it for data that belongs together and shouldn't change, like coordinates. Unpacking splits a tuple into several variables in one line.

tuple.py
library = (32.0853, 34.7818)
lat, lon = library
print(lat, lon)
book = ("Dune", 1965)
title, year = book
print(f"{title} יצא ב- {year}")
print(divmod(412, 30))
library = (32.0853, 34.7818)
lat, lon = library
print(lat, lon)
book = ("Dune", 1965)
title, year = book
print(f"{title} came out in {year}")
print(divmod(412, 30))
פלטOutput
32.0853 34.7818
Dune יצא ב- 1965
(13, 22)
32.0853 34.7818
Dune came out in 1965
(13, 22)
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

טאפל הוא כמו תאריך לידה בתעודת זהות: מודפס פעם אחת, ואף אחד לא אמור לשנות אותו.

A tuple is like the date of birth on an ID card: printed once, and nobody should change it.

טעות נפוצהCommon mistake

מנסים לשנות טאפל.

Trying to change a tuple.

tuple.py
point = (3, 4)
point[0] = 10
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/tuple.py", line 2, in <module>
    point[0] = 10
    ~~~~~^^^
TypeError: 'tuple' object does not support item assignment
בעברית פשוטה: In plain words: TypeError: 'tuple' object does not support item assignment: יוצרים טאפל חדש, או משתמשים ברשימה אם הנתונים אמורים להשתנות.TypeError: 'tuple' object does not support item assignment: make a new tuple, or use a list if the data should change.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05סטים: בלי כפילויותSets: no duplicates

סט שומר כל ערך פעם אחת בלבד, ובלי סדר. הוא מצוין להסרת כפילויות, לבדיקת in מהירה, ולהשוואת קבוצות: מה משותף, מה האיחוד, מה ההבדל.

A set keeps each value once, with no order. It's great for removing duplicates, fast in checks, and comparing groups: what's common, the union, the difference.

sets.py
noa = {"Dune", "Emma", "Matilda"}
dan = {"Dune", "Ulysses"}
print(sorted(noa & dan))
print(sorted(noa | dan))
print(sorted(noa - dan))
tags = ["sci-fi", "kids", "sci-fi"]
print(len(set(tags)))
פלטOutput
['Dune']
['Dune', 'Emma', 'Matilda', 'Ulysses']
['Emma', 'Matilda']
2
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

סט הוא כמו רשימת מוזמנים לחתונה: כל שם מופיע פעם אחת, ולא משנה באיזה סדר נרשם.

A set is like a wedding guest list: each name appears once, and the order doesn't matter.

טיפTip

סט ריק כותבים set(). הצורה {} היא מילון ריק.

An empty set is set(). {} is an empty dict.

טעות נפוצהCommon mistake

פונים לסט לפי אינדקס.

Indexing into a set.

sets.py
tags = {"sci-fi", "kids"}
print(tags[0])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/sets.py", line 2, in <module>
    print(tags[0])
          ~~~~^^^
TypeError: 'set' object is not subscriptable
בעברית פשוטה: In plain words: TypeError: 'set' object is not subscriptable: לסט אין סדר. ממירים לרשימה: sorted(tags)[0].TypeError: 'set' object is not subscriptable: a set has no order. Convert to a list: sorted(tags)[0].
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

set שומר כל ערך פעם אחת, ויודע למצוא מה משותף.

A set keeps each value once, and can find what's shared.

עוד דוגמה: מי בא לשתי המסיבותOne more: who came to both parties
example.py
party1 = {"Noa", "Dan", "Lia"}
party2 = {"Dan", "Ari", "Lia"}
print(sorted(party1 & party2))
print(sorted(party1 | party2))
פלטOutput
['Dan', 'Lia']
['Ari', 'Dan', 'Lia', 'Noa']
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06איזה מבנה לבחור?Which structure to choose?

השאלה "איזה מבנה?" מופיעה בכל תוכנית, וגם בכל ראיון עבודה. שאלו: האם הסדר חשוב? האם מחפשים לפי שם? האם הנתונים משתנים? האם מותרות כפילויות?

"Which structure?" comes up in every program and in every job interview. Ask: does order matter? Do I look things up by name? Does the data change? Are duplicates allowed?

מבנהStructureסדרOrderedשינויChangeableכפילויותDuplicatesדוגמהExample
list []כןYesכןYesכןYesספרים על המדףBooks on the shelf
dict {k: v}כן (לפי הכנסה)Yes (insertion)כןYesמפתחות לאKeys noפרטי ספרA book's details
tuple ()כןYesלאNoכןYesקואורדינטהA coordinate
set {}לאNoכןYesלאNoז'אנריםGenres
choose.py
book = {
    "title": "Dune",
    "location": (3, 2),
    "genres": {"sci-fi", "classic"},
    "quotes": ["Fear is the mind-killer."],
}
book["genres"].add("sci-fi")
print(len(book["genres"]), book["location"][0])
פלטOutput
2 3
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

זה כמו לבחור כלי אחסון בבית: מדף לספרים לפי סדר, מגירה עם תוויות לפי שם, כספת לדברים שלא משתנים, וקופסת "פעם אחת מכל דבר" לאוסף.

It's like choosing storage at home: a shelf for books in order, labelled drawers by name, a safe for things that don't change, and a "one of each" box for a collection.

טעות נפוצהCommon mistake

משתמשים ברשימה כמפתח במילון. מפתח חייב להיות immutable.

Using a list as a dict key. A key must be immutable.

choose.py
seats = {}
seats[[3, 2]] = "Dune"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/choose.py", line 2, in <module>
    seats[[3, 2]] = "Dune"
    ~~~~~^^^^^^^^
TypeError: unhashable type: 'list'
בעברית פשוטה: In plain words: TypeError: unhashable type: 'list': משתמשים בטאפל: seats[(3, 2)] = "Dune".TypeError: unhashable type: 'list': use a tuple: seats[(3, 2)] = "Dune".
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich