רשימותLists
יצירה, הוספה, מחיקה, מיון, ומה זה mutable.
Creating, adding, removing, sorting, and what mutable means.
01רשימות: הרבה ערכים בשם אחדLists: many values under one name
רשימה שומרת כמה ערכים לפי סדר. אינדקסים וחיתוך עובדים בדיוק כמו במחרוזות, ופונקציות כמו len, sum ו-max עובדות עליה ישירות.
A list holds several values in order. Indexing and slicing work exactly as with strings, and functions like len, sum and max work on it directly.
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))Dune Matilda ['Emma', 'Ulysses'] 4 True 1856 730 240
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
רשימה היא כמו מדף עם תאים ממוספרים. אפשר להוסיף תא, להוציא ספר מתא, או לסדר את כל המדף מחדש.
A list is like a shelf with numbered slots. You can add a slot, take a book out of a slot, or rearrange the whole shelf.
פונים לאינדקס שלא קיים.
Asking for an index that doesn't exist.
books = ["Dune", "Emma"]
print(books[2])Traceback (most recent call last):
File "/Users/you/python-course/lists.py", line 2, in <module>
print(books[2])
~~~~~^^^
IndexError: list index out of rangeIndexError: list index out of range: ברשימה של 2 פריטים האינדקסים הם 0 ו-1.IndexError: list index out of range: a 2-item list has indexes 0 and 1.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02לשנות רשימהChanging a list
בניגוד למחרוזות, רשימות הן משתנה (mutable): אפשר לשנות אותן במקום. append מוסיף לסוף, insert במקום מסוים, remove מוחק לפי ערך, pop מוציא לפי מקום ומחזיר את מה שהוציא.
Unlike strings, lists are mutable: they can change in place. append adds to the end, insert at a position, remove deletes by value, and pop takes out by position and returns what it took.
shelf = ["Dune"]
shelf.append("Emma")
shelf.insert(0, "Matilda")
print(shelf)
shelf[1] = "Dune Messiah"
last = shelf.pop()
print(last, shelf)
shelf.remove("Matilda")
print(shelf)['Matilda', 'Dune', 'Emma'] Emma ['Matilda', 'Dune Messiah'] ['Dune Messiah']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
append הוא להניח ספר בסוף המדף. insert הוא לדחוף ספר באמצע ולהזיז את השאר. pop הוא לשלוף ספר ולהחזיק אותו ביד.
append is putting a book at the end of the shelf. insert is pushing one into the middle and shifting the rest. pop is pulling a book out and holding it.
מוחקים ערך שלא נמצא ברשימה.
Removing a value that isn't in the list.
shelf = ["Dune", "Emma"]
shelf.remove("Ulysses")Traceback (most recent call last):
File "/Users/you/python-course/change.py", line 2, in <module>
shelf.remove("Ulysses")
~~~~~~~~~~~~^^^^^^^^^^^
ValueError: list.remove(x): x not in listValueError: 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:.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מוסיפים, מוחקים ומשנים פריטים ברשימה.
Add, remove and change items in a list.
shop = ["milk", "eggs"]
shop.append("bread")
shop.remove("eggs")
shop[0] = "oat milk"
print(shop, len(shop))['oat milk', 'bread'] 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03mutable מול immutable: שני שמות לאותה רשימהMutable vs immutable: two names, one list
b = a לא יוצר רשימה חדשה: הוא מדביק עוד שם על אותה רשימה. זה נקרא כינוי. עם מחרוזות ומספרים זה לא משנה (הם בלתי משתנה (immutable)), אבל עם רשימות שינוי דרך שם אחד נראה בשני. הוויזואלייזר מראה את זה בבירור:
b = a doesn't make a new list: it sticks another name on the same list. That's an alias. With strings and numbers it doesn't matter (they're immutable), but with lists a change through one name shows in the other. The visualizer makes it clear:
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
b = a הוא כמו לתת לחבר מפתח לדירה שלך, לא דירה משלו. אם הוא מזיז רהיטים, תראה את זה כשתחזור הביתה.
b = a is like giving a friend a key to your flat, not a flat of their own. If they move the furniture, you'll see it when you get home.
מתודות כמו sort ו-append מחזירות None. כששומרים את התוצאה שלהן, מאבדים את הרשימה.
Methods like sort and append return None. Saving their result loses the list.
books = ["Emma", "Dune"]
books = books.sort()
print(books[0])Traceback (most recent call last):
File "/Users/you/python-course/mutable.py", line 3, in <module>
print(books[0])
~~~~~^^^
TypeError: 'NoneType' object is not subscriptableTypeError: '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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04לולאות על רשימותLooping over lists
for על רשימה נותן כל פריט בתורו. כשצריך גם את המספר הסידורי, enumerate נותנת זוגות של (מספר, פריט). דפוס נפוץ: רשימה ריקה ו-append בתוך לולאה.
for over a list gives each item in turn. When you also need the position, enumerate gives (number, item) pairs. A common pattern: an empty list plus append inside a loop.
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)
print(short)1. Dune 2. Emma 3. Ulysses ['Dune', 'Emma']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
enumerate היא כמו מדבקות ממוספרות שמדביקים על כל ספר רגע לפני שבודקים אותו.
enumerate is like numbered stickers you put on each book just before checking it.
משנים את הרשימה תוך כדי מעבר עליה, ומדלגים בטעות על פריטים. כאן בדיקה חושפת את זה.
Changing a list while looping over it, which accidentally skips items. A check here exposes it.
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
assert 2 not in nums, f"still has a 2: {nums}"Traceback (most recent call last):
File "/Users/you/python-course/loop.py", line 5, in <module>
assert 2 not in nums, f"still has a 2: {nums}"
^^^^^^^^^^^^^
AssertionError: still has a 2: [1, 2, 3]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].צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05מיוןSorting
lst.sort() ממיינת את הרשימה עצמה. sorted(lst) משאירה את המקור ומחזירה רשימה ממוינת חדשה. אפשר למיין הפוך, או לפי מפתח כמו אורך.
lst.sort() sorts the list itself. sorted(lst) leaves the original and returns a new sorted list. You can sort in reverse, or by a key such as length.
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))[96, 280, 412, 1036] [412, 96, 1036, 280] [1036, 412, 280, 96] ['Dune', 'Emma', 'Ulysses']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
sort הוא לסדר את המדף עצמו. sorted הוא לצלם את המדף ולסדר את התמונה, בלי לגעת בספרים.
sort is tidying the shelf itself. sorted is photographing the shelf and arranging the photo, without touching the books.
ממיינים רשימה עם טיפוסים מעורבים.
Sorting a list with mixed types.
mixed = [3, "two", 1]
mixed.sort()Traceback (most recent call last):
File "/Users/you/python-course/sort.py", line 2, in <module>
mixed.sort()
~~~~~~~~~~^^
TypeError: '<' not supported between instances of 'str' and 'int'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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06list comprehension ו-split/joinList comprehensions and split/join
list comprehension בונה רשימה חדשה בשורה אחת: "תן לי X עבור כל פריט, אולי רק אם...". split מפרק מחרוזת לרשימה, ו-join מחבר רשימת מחרוזות למחרוזת אחת.
A list comprehension builds a new list in one line: "give me X for every item, maybe only if...". split breaks a string into a list, and join glues a list of strings into one.
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(",")
print(books)
print(" | ".join(books))[10.3, 2.4, 25.9, 7.0] [412, 1036] ['Dune', 'Emma', 'Ulysses'] Dune | Emma | Ulysses
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
comprehension הוא כמו להגיד לעוזר "תעבור על כל הספרים ותביא לי רק את הארוכים", במקום להסביר לו צעד אחר צעד.
A comprehension is like telling an assistant "go through all the books and bring me just the long ones", instead of explaining step by step.
join עובד רק על מחרוזות.
join only works on strings.
pages = [412, 96]
print(", ".join(pages))Traceback (most recent call last):
File "/Users/you/python-course/comp.py", line 2, in <module>
print(", ".join(pages))
~~~~~~~~~^^^^^^^
TypeError: sequence item 0: expected str instance, int foundTypeError: 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).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
list comprehension בונה רשימה חדשה בשורה אחת.
A list comprehension builds a new list in one line.
nums = [1, 2, 3, 4]
doubled = [n * 2 for n in nums]
big = [n for n in nums if n > 2]
print(doubled, big)[2, 4, 6, 8] [3, 4]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.