חלקPart 1: יסודותFoundations
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
רשימותLists
יצירה, הוספה, מחיקה, מיון, ומה זה mutable.
Creating, adding, removing, sorting, and what mutable means.
הנקודות החשובותKey points
[a, b, c]בסוגריים מרובעים[a, b, c]in square brackets- אינדקסים וחיתוך כמו במחרוזתIndexing and slicing like strings
.append(x)מוסיף לסוף.append(x)adds to the end.remove(x),.pop(),del.remove(x),.pop(),delb = aלא מעתיק רשימהb = adoesn't copy a list- שינוי דרך b נראה גם דרך aA change through b shows through a
for book in books:for book in books:enumerateנותן גם מספרenumeratealso gives a number.sort()משנה את הרשימה.sort()changes the list
מונחיםTerms
- רשימה (list)list: רצף מסודר של ערכים בסוגריים מרובעים:
[1, 2, 3]. אפשר לשנות אותה.An ordered sequence of values in square brackets:[1, 2, 3]. It can be changed. - משתנה (mutable)mutable: ערך שאפשר לשנות במקום, בלי ליצור חדש. רשימות ומילונים הם mutable.A value that can be changed in place, without making a new one. Lists and dicts are mutable.
- כינוי (alias)alias: שני שמות שמצביעים על אותו אובייקט. שינוי דרך אחד נראה גם דרך השני.Two names pointing at the same object. A change through one shows through the other.
- list comprehensionlist comprehension: בניית רשימה בשורה אחת:
[x * 2 for x in nums].Building a list in one line:[x * 2 for x in nums]. - enumerateenumerate: נותנת גם מספר וגם פריט בלולאה:
for i, x in enumerate(items).Gives both a number and an item in a loop:for i, x in enumerate(items).
Cheatsheet
רשימותLists
books = ["Dune", "Emma", "Ulysses", "Matilda"]
print(books[0], books[-1])
print(books[1:3])
print(len(books), "Emma" in books)
pages = [412, 474, 730, 240]
print(sum(pages), max(pages), min(pages))שינוי רשימהChanging lists
shelf = ["Dune"]
shelf.append("Emma")
shelf.insert(0, "Matilda")
print(shelf)
shelf[1] = "Dune Messiah"
last = shelf.pop()
print(last, shelf)לולאותLooping
books = ["Dune", "Emma", "Ulysses"]
for i, title in enumerate(books, start=1):
print(f"{i}. {title}")
short = []
for title in books:
if len(title) <= 4:
short.append(title)מיוןSorting
pages = [412, 96, 1036, 280]
print(sorted(pages))
print(pages)
pages.sort(reverse=True)
print(pages)
books = ["Ulysses", "Dune", "Emma"]
print(sorted(books, key=len))comprehensionComprehensions
pages = [412, 96, 1036, 280]
hours = [round(p / 40, 1) for p in pages]
print(hours)
long = [p for p in pages if p > 300]
print(long)
line = "Dune,Emma,Ulysses"
books = line.split(",")שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
IndexError | פונים לאינדקס שלא קיים.Asking for an index that doesn't exist. | IndexError: list index out of range: ברשימה של 2 פריטים האינדקסים הם 0 ו-1.IndexError: list index out of range: a 2-item list has indexes 0 and 1. |
ValueError | מוחקים ערך שלא נמצא ברשימה.Removing a value that isn't in the list. | ValueError: list.remove(x): x not in list: בודקים קודם עם if x in shelf:.ValueError: list.remove(x): x not in list: check first with if x in shelf:. |
TypeError | מתודות כמו sort ו-append מחזירות None. כששומרים את התוצאה שלהן, מאבדים את הרשימה.Methods like sort and append return None. Saving their result loses the list. | TypeError: 'NoneType' object is not subscriptable: sort ממיינת במקום. כותבים רק books.sort(), או sorted(books) לרשימה חדשה.TypeError: 'NoneType' object is not subscriptable: sort sorts in place. Write just books.sort(), or sorted(books) for a new list. |
AssertionError | משנים את הרשימה תוך כדי מעבר עליה, ומדלגים בטעות על פריטים. כאן בדיקה חושפת את זה.Changing a list while looping over it, which accidentally skips items. A check here exposes it. | AssertionError: אחרי מחיקה הפריטים זזים, והלולאה דילגה על ה-2 השני. בונים רשימה חדשה במקום: [n for n in nums if n != 2].AssertionError: after a removal items shift, and the loop skipped the second 2. Build a new list instead: [n for n in nums if n != 2]. |
TypeError | ממיינים רשימה עם טיפוסים מעורבים.Sorting a list with mixed types. | TypeError: '<' not supported between instances of 'str' and 'int': Python לא יודעת אם "two" לפני או אחרי 3. ממירים לטיפוס אחד.TypeError: '<' not supported between instances of 'str' and 'int': Python can't tell if "two" comes before or after 3. Convert to one type. |
TypeError | join עובד רק על מחרוזות.join only works on strings. | TypeError: sequence item 0: expected str instance, int found: ממירים: ", ".join(str(p) for p in pages).TypeError: sequence item 0: expected str instance, int found: convert: ", ".join(str(p) for p in pages). |