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

חזרה למפגשBack
PythonPython

רשימותLists

מפגש 7: יצירה, הוספה, מחיקה, מיון, ומה זה mutable.Session 7: Creating, adding, removing, sorting, and what mutable means.

מה נעשה היוםToday's plan

  • רשימותLists
  • שינוי רשימהChanging lists
  • mutableMutable
  • לולאותLooping
  • מיוןSorting
  • comprehensionComprehensions
נושאTopic 1

רשימותLists

רשימות: הרבה ערכים בשם אחדLists: many values under one name

  • [a, b, c] בסוגריים מרובעים[a, b, c] in square brackets
  • אינדקסים וחיתוך כמו במחרוזתIndexing and slicing like strings
  • len, in, min, max, sumlen, in, min, max, sum

אנלוגיהAnalogy

רשימה היא כמו מדף עם תאים ממוספרים. אפשר להוסיף תא, להוציא ספר מתא, או לסדר את כל המדף מחדש.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.

טעות נפוצהCommon mistake

lists.py
books = ["Dune", "Emma"]
print(books[2])
מה Python עונהWhat Python says
IndexError: list index out of range
IndexError: list index out of range: ברשימה של 2 פריטים האינדקסים הם 0 ו-1.IndexError: list index out of range: a 2-item list has indexes 0 and 1.
נושאTopic 2

שינוי רשימהChanging lists

לשנות רשימהChanging a list

  • .append(x) מוסיף לסוף.append(x) adds to the end
  • .remove(x), .pop(), del.remove(x), .pop(), del
  • lst[i] = x מחליףlst[i] = x replaces
שאלה לכיתהQuestion for the class

מה ידפיס הקוד?What will this print?

python
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)

    שינוי רשימהChanging lists

    change.py
    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)
    פלטOutput
    ['Matilda', 'Dune', 'Emma']
    Emma ['Matilda', 'Dune Messiah']
    ['Dune Messiah']

    אנלוגיהAnalogy

    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.

    טעות נפוצהCommon mistake

    change.py
    shelf = ["Dune", "Emma"]
    shelf.remove("Ulysses")
    מה Python עונהWhat Python says
    ValueError: list.remove(x): x not in 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:.
    נושאTopic 3

    mutableMutable

    mutable מול immutable: שני שמות לאותה רשימהMutable vs immutable: two names, one list

    • b = a לא מעתיק רשימהb = a doesn't copy a list
    • שינוי דרך b נראה גם דרך aA change through b shows through a
    • להעתקה: a.copy() או a[:]To copy: a.copy() or a[:]

    אנלוגיהAnalogy

    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.

    טעות נפוצהCommon mistake

    mutable.py
    books = ["Emma", "Dune"]
    books = books.sort()
    print(books[0])
    מה Python עונהWhat Python says
    TypeError: 'NoneType' object is not subscriptable
    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.
    נושאTopic 4

    לולאותLooping

    לולאות על רשימותLooping over lists

    • for book in books:for book in books:
    • enumerate נותן גם מספרenumerate also gives a number
    • בונים רשימה חדשה עם append בלולאהBuild a new list with append in a loop
    שאלה לכיתהQuestion for the class

    מה ידפיס הקוד?What will this print?

    python
    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)

      לולאותLooping

      loop.py
      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)
      פלטOutput
      1. Dune
      2. Emma
      3. Ulysses
      ['Dune', 'Emma']

      אנלוגיהAnalogy

      enumerate היא כמו מדבקות ממוספרות שמדביקים על כל ספר רגע לפני שבודקים אותו.enumerate is like numbered stickers you put on each book just before checking it.
      נושאTopic 5

      מיוןSorting

      מיוןSorting

      • .sort() משנה את הרשימה.sort() changes the list
      • sorted() מחזיר רשימה חדשהsorted() returns a new list
      • reverse=True, key=lenreverse=True, key=len
      שאלה לכיתהQuestion for the class

      מה ידפיס הקוד?What will this print?

      python
      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))

        מיוןSorting

        sort.py
        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))
        פלטOutput
        [96, 280, 412, 1036]
        [412, 96, 1036, 280]
        [1036, 412, 280, 96]
        ['Dune', 'Emma', 'Ulysses']

        אנלוגיהAnalogy

        sort הוא לסדר את המדף עצמו. sorted הוא לצלם את המדף ולסדר את התמונה, בלי לגעת בספרים.sort is tidying the shelf itself. sorted is photographing the shelf and arranging the photo, without touching the books.

        טעות נפוצהCommon mistake

        sort.py
        mixed = [3, "two", 1]
        mixed.sort()
        מה Python עונהWhat Python says
        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.
        נושאTopic 6

        comprehensionComprehensions

        list comprehension ו-split/joinList comprehensions and split/join

        • [x * 2 for x in nums][x * 2 for x in nums]
        • עם תנאי: [x for x in nums if x > 0]With a filter: [x for x in nums if x > 0]
        • split מטקסט לרשימה, join חזרהsplit text to list, join back
        שאלה לכיתהQuestion for the class

        מה ידפיס הקוד?What will this print?

        python
        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))

          comprehensionComprehensions

          comp.py
          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))
          פלטOutput
          [10.3, 2.4, 25.9, 7.0]
          [412, 1036]
          ['Dune', 'Emma', 'Ulysses']
          Dune | Emma | Ulysses

          אנלוגיהAnalogy

          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.

          טעות נפוצהCommon mistake

          comp.py
          pages = [412, 96]
          print(", ".join(pages))
          מה Python עונהWhat Python says
          TypeError: sequence item 0: expected str instance, int found
          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).

          [a, b, c] בסוגריים מרובעים[a, b, c] in square brackets

          אינדקסים וחיתוך כמו במחרוזתIndexing and slicing like strings

          len, in, min, max, sumlen, in, min, max, sum

          .append(x) מוסיף לסוף.append(x) adds to the end

          .remove(x), .pop(), del.remove(x), .pop(), del

          מה למדנוWhat we learned

          • [a, b, c] בסוגריים מרובעים[a, b, c] in square brackets
          • .append(x) מוסיף לסוף.append(x) adds to the end
          • b = a לא מעתיק רשימהb = a doesn't copy a list
          • for book in books:for book in books:
          • .sort() משנה את הרשימה.sort() changes the list
          • [x * 2 for x in nums][x * 2 for x in nums]

          עכשיו לתרגולNow, practice

          5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
          הערות מרצהSpeaker notes

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