נבנה על ידיBuilt by Ariel Yohimovich
[a, b, c] בסוגריים מרובעים[a, b, c] in square bracketslen, in, min, max, sumlen, in, min, max, sumlen, 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"]
print(books[2])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..append(x) מוסיף לסוף.append(x) adds to the end.remove(x), .pop(), del.remove(x), .pop(), dellst[i] = x מחליףlst[i] = x replacesappend מוסיף לסוף, 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)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']
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.shelf = ["Dune", "Emma"]
shelf.remove("Ulysses")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:.b = a לא מעתיק רשימהb = a doesn't copy a lista.copy() או a[:]To copy: a.copy() or a[:]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: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.books = ["Emma", "Dune"]
books = books.sort()
print(books[0])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.sort ו-append מחזירות None. כששומרים את התוצאה שלהן, מאבדים את הרשימה.Methods like sort and append return None. Saving their result loses the list.for book in books:for book in books:enumerate נותן גם מספרenumerate also gives a numberfor על רשימה נותן כל פריט בתורו. כשצריך גם את המספר הסידורי, 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)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']
.sort() משנה את הרשימה.sort() changes the listsorted() מחזיר רשימה חדשהsorted() returns a new listreverse=True, key=lenreverse=True, key=lenlst.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))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']
sort הוא לסדר את המדף עצמו. sorted הוא לצלם את המדף ולסדר את התמונה, בלי לגעת בספרים.sort is tidying the shelf itself. sorted is photographing the shelf and arranging the photo, without touching the books.mixed = [3, "two", 1]
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.[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 backsplit מפרק מחרוזת לרשימה, ו-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))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
pages = [412, 96]
print(", ".join(pages))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).join עובד רק על מחרוזות.join only works on strings.[a, b, c] בסוגריים מרובעים[a, b, c] in square bracketslen, in, min, max, sumlen, in, min, max, sum.append(x) מוסיף לסוף.append(x) adds to the end.remove(x), .pop(), del.remove(x), .pop(), del[a, b, c] בסוגריים מרובעים[a, b, c] in square brackets.append(x) מוסיף לסוף.append(x) adds to the endb = a לא מעתיק רשימהb = a doesn't copy a listfor book in books:for book in books:.sort() משנה את הרשימה.sort() changes the list[x * 2 for x in nums][x * 2 for x in nums]נבנה על ידיBuilt by Ariel Yohimovich