PythonPython · Chapterبەش 9 · Lectureوانە 9.3
Removing Items, Joining and Comparing Listsلابردنی دانەکان، پێکەوەلکاندن و بەراوردکردنی لیستەکان
Removing elements by position with pop() and del and by value with remove(), removing safely, clear(), Lab 3 Task 2, joining lists with + and repeating them with *, and comparing lists with ==, != and the lexicographic < and >.
لابردنی بە شوێن بە pop() و del و بە بە remove()، لابردن بە سەلامەتی، clear()، ئەرکی 2ی تاقیگەی 3، بە + و دووبارەکردنەوەیان بە *. هەروەها بەراوردکردنی بە ==، != و بە < و >ی فەرهەنگی.
What you will learnچی فێر دەبیت
- Remove elements by position (
pop(),del) and by value (remove()), and use whatpop()returns. - Avoid
IndexErrorandValueErrorwhen removing, and avoid removing inside a loop over the same list. - Join lists with
+, repeat them with*, and know which operations make a new list. - Compare lists with
==,!=,<and>and explain the result pair by pair.
- بە شوێن (
pop()،del) و بە (remove()) لاببەیت و ئەوەیpop()دەیگەڕێنێتەوە بەکار بهێنیت. - لە کاتی لابردندا خۆت لە
IndexErrorوValueErrorبپارێزیت و لە ناو بەسەر هەمان لای نەبەیت. - بە
+پێکەوە بلکێنیت، بە*دووبارەیان بکەیتەوە و بزانیت کام کار نوێ دروست دەکات. - بە
==،!=،<و>بەراورد بکەیت و ئەنجامەکە جووت بە جووت ڕوون بکەیتەوە.
Removing elements: by position or by valueلابردنی دانەکان: بە شوێن یان بە نرخ
There are two ways to say which element should go. By position: "remove the element at index 1", with the pop() method (or the del statement). By value: "remove 'apple', wherever it is", with the remove() method. clear() empties the whole list. In every case the list itself changes and gets shorter.
دوو ڕێگە هەیە بۆ گوتنی ئەوەی کام لاببرێت. بە شوێن: « 1 لاببە»، بە pop() (یان del). بە : «'apple' لاببە، لە هەر کوێیەک بێت»، بە remove(). clear() هەموو بەتاڵ دەکاتەوە. لە هەموو حاڵەتێکدا خودی دەگۆڕێت و کورتتر دەبێت.
| Toolئامراز | Removesچی لادەبات | Gives backچی دەگەڕێنێتەوە | When it cannotکاتێک ناتوانێت |
|---|---|---|---|
a.pop(i) | the element at index i i | that elementهەمان | IndexError |
a.pop() | the last elementدوایین | that elementهەمان | IndexError |
a.remove(x) | the first element equal to xیەکەم کە یەکسانە بە x | None | ValueError |
del a[i] | the element at index i (also slices) i () | nothing: it is a statementهیچ: | IndexError |
a.clear() | every elementهەموو | None | never failsهەرگیز شکست ناهێنێت |
Making lists and reaching, changing and slicing their elements by index; later chapters remove elements and find where a value is.
دروستکردنی ، خوێندنەوە، گۆڕین و بە ؛ بەشەکانی دواتر لادەبەن و شوێنی دەدۆزنەوە.
Watch 15:07–16:56: pop(), pop(0), remove('b'), del with a slice and clear().
لە 15:07 تا 16:56 سەیر بکە: pop()، pop(0)، remove('b')، del لەگەڵ و clear().
pop(): remove by positionpop(): لابردن بە شوێن
pop(i) removes the element at index i. All the elements after it move one place to the left to close the gap, and the list gets shorter by 1. The index must be valid, exactly as when you read an element.
pop(i) i لادەبات. هەموو دوای ئەو یەک شوێن بەرەو چەپ دەجووڵێن بۆ داخستنی بۆشاییەکە و 1 کورتتر دەبێت. دەبێت دروست بێت، ڕێک وەک کاتی خوێندنەوەی .
fruits = ['apple', 'orange', 'banana']
fruits.pop(1)
print(fruits)['apple', 'banana']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
'orange' (index 1) goes; 'banana' moves from index 2 to index 1.
'orange' ( 1) دەڕوات؛ 'banana' لە 2ەوە دەچێتە 1.
![Animation of three lines of code. fruits = ['apple', 'orange', 'banana', 'kiwi'] shows four boxes at indexes 0 to 3. taken = fruits.pop(1): the 'orange' box is lifted out of index 1, leaving a dashed gap; then 'banana' and 'kiwi' slide one place to the left, to indexes 1 and 2, the variable box taken holds 'orange', and len(fruits) is 3. fruits.remove('kiwi'): 'apple' and 'banana' are crossed out as not equal, 'kiwi' is ticked; then 'kiwi' is taken out and the result is ['apple', 'banana'] with len(fruits) = 2.](/_astro/py-removing-and-combining-lists-pop-remove.en.BJb4qWZX.gif)
![Animation of three lines of code. fruits = ['apple', 'orange', 'banana', 'kiwi'] shows four boxes at indexes 0 to 3. taken = fruits.pop(1): the 'orange' box is lifted out of index 1, leaving a dashed gap; then 'banana' and 'kiwi' slide one place to the left, to indexes 1 and 2, the variable box taken holds 'orange', and len(fruits) is 3. fruits.remove('kiwi'): 'apple' and 'banana' are crossed out as not equal, 'kiwi' is ticked; then 'kiwi' is taken out and the result is ['apple', 'banana'] with len(fruits) = 2.](/_astro/py-removing-and-combining-lists-pop-remove.ckb.D04oSPJE.gif)
pop() بە کار دەکات و دەگەڕێنێتەوە؛ remove() بەدوای دەگەڕێت.CêITpop(): remove by positionpop(): لابردن بە شوێن
pop() gives the element backpop() دانەکە دەگەڕێنێتەوە
Unlike remove(), pop() returns the element it removes, so you can store it in a variable and use it. With no index at all, pop() removes and returns the last element, which is perfect for an "undo" list. A list used only with append() and pop() is a stack: see A Python list as a stack. Two things raise IndexError: an index outside the list, and popping from an empty list.
بە پێچەوانەی remove()ـەوە، pop() ئەو لایدەبات دەیگەڕێنێتەوە، بۆیە دەتوانیت لە هەڵیبگریت و بەکاری بهێنیت. بەبێ هیچ ، pop() دوایین لادەبات و دەیگەڕێنێتەوە، کە بۆ تەواوە. کە تەنها بە append() و pop() بەکار بێت : بڕوانە لیستێکی Python وەک ستاک. دوو شت IndexError دروست دەکەن: لە دەرەوەی و pop لە بەتاڵ.
pop() دەیگەڕێنێتەوەpop_returns.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange', 'banana']
last = fruits.pop()
print(last, fruits)
second = fruits.pop(1)
print(second, fruits)
print(len(fruits))banana ['apple', 'orange'] orange ['apple'] 1
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
No index: the last element, 'banana', is removed and returned.
بەبێ : دوایین ، 'banana'، لادەبرێت و دەگەڕێنرێتەوە.
- Lineدێڕی 4
With an index: 'orange' is removed and stored in
second.بە : 'orange' لادەبرێت و لە
secondدا هەڵدەگیرێت.
fruits = ['apple', 'orange', 'banana']
fruits.pop(5)Traceback (most recent call last):
File "pop_error.py", line 2, in <module>
fruits.pop(5)
IndexError: pop index out of rangefruits = []
fruits.pop()Traceback (most recent call last):
File "pop_empty.py", line 2, in <module>
fruits.pop()
IndexError: pop from empty listremove(): remove by valueremove(): لابردن بە نرخ
remove(x) removes an element by value instead of by position: Python looks for an element equal to x and takes it out. It searches like in, from index 0, and removes only the first match; later copies stay.
remove(x) بە لادەبات نەک بە شوێن: بەدوای دەگەڕێت کە یەکسان بێت بە x و دەریدەهێنێت. وەک in دەگەڕێت، لە 0ەوە و تەنها یەکەم هاوتا لادەبات؛ کۆپییەکانی دواتر دەمێننەوە.
fruits = ['apple', 'orange', 'banana']
fruits.remove('apple')
print(fruits)['orange', 'banana']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The value 'apple' is found at index 0 and removed.
'apple' لە 0دا دەدۆزرێتەوە و لادەبرێت.
fruits = ['orange', 'apple', 'banana', 'apple']
fruits.remove('apple')
print(fruits)['orange', 'banana', 'apple']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The 'apple' at index 1 is removed; the one at the end stays.
'apple'ـی 1 لادەبرێت؛ ئەوەی کۆتایی دەمێنێتەوە.
remove(): remove by valueremove(): لابردن بە نرخ
Removing safelyلابردن بە سەلامەتی
The value you remove must be in the list, or Python raises a ValueError and the program stops. To avoid this run-time error, first check that the element is in the list, then remove it.
ئەو لایدەبەیت دەبێت لە بێت، ئەگەرنا ValueError دروست دەکات و دەوەستێت. بۆ ڕێگرتن لەم ، سەرەتا بپشکنە کە لە ، پاشان لای ببە.
fruits = ['apple', 'orange', 'banana']
fruits.remove('kiwi')
print(fruits)Traceback (most recent call last):
File "remove_error.py", line 2, in <module>
fruits.remove('kiwi')
ValueError: list.remove(x): x not in listfruits = ['apple', 'orange', 'banana']
if 'kiwi' in fruits:
fruits.remove('kiwi')
print(fruits)['apple', 'orange', 'banana']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
'kiwi' is not there, so
remove()is never called and nothing breaks.'kiwi' لەوێ نییە، بۆیە
remove()هەرگیز بانگ ناکرێت و هیچ تێک ناچێت.
del and clear()del و clear()
del is a statement, not a method: del a[i] removes the element at index i, like pop(i), but gives nothing back. It also removes a whole slice, del a[1:3], even one with a step, del a[::2]. a.clear() removes every element and leaves an empty list. Finally, del a deletes the name a itself; using it afterwards is a NameError.
del ، نەک : del a[i] i لادەبات، وەک pop(i)، بەڵام هیچ ناگەڕێنێتەوە. هەروەها دەتوانێت بە چەند پێکەوە لاببات، del a[1:3]، تەنانەت بە هەنگاویشەوە، del a[::2]. a.clear() هەموو لادەبات و بەتاڵ دەهێڵێتەوە. لە کۆتاییدا، del a خودی ناوی a دەسڕێتەوە؛ بەکارهێنانی دواتری NameErrorـە.
del بە ئیندێکس و لەتکردن، پاشان clear()del_clear.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەnumbers = [10, 20, 30, 40, 50]
del numbers[0]
print(numbers)
del numbers[1:3]
print(numbers)
numbers.clear()
print(numbers, len(numbers))[20, 30, 40, 50] [20, 50] [] 0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Index 0 (10) goes.
0 (10) دەڕوات.
- Lineدێڕی 4
The slice 1:3 removes indexes 1 and 2 (30 and 40).
1:3 1 و 2 (30 و 40) لادەبات.
- Lineدێڕی 6
Every element goes; the list still exists, empty.
هەموو دەڕۆن؛ هێشتا هەیە، بەتاڵ.
del خودی ناوەکە لادەباتdel_name.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەshopping = ["bread", "tea", "sugar"]
del shopping
print(shopping)Traceback (most recent call last):
File "del_name.py", line 3, in <module>
print(shopping)
^^^^^^^^
NameError: name 'shopping' is not definedLab 3, Task 2: remove Logic, or the last moduleتاقیگەی 3، ئەرکی 2: Logic لاببە، یان دوایین وانە
Create a list of the modules Programming, Mathematics, English and Logic. Then search the list: if it contains "Logic", remove it; otherwise remove the last element. Print the list before and after.
لە وانەکانی Programming، Mathematics، English و Logic دروست بکە. پاشان لە بگەڕێ: ئەگەر "Logic"ی تێدا بوو، لای ببە؛ ئەگەرنا دوایین لاببە. پێش و دوای ئەوە چاپ بکە.
Hintئاماژە
if "Logic" in modules: … else: …
if "Logic" in modules: … else: …
Show answerوەڵامەکە پیشان بدە
modules = ["Programming", "Mathematics", "English", "Logic"]
print("The list before Update ", modules)
if "Logic" in modules:
modules.remove("Logic")
else:
modules.pop()
print("The list after Update", modules)The list before Update ['Programming', 'Mathematics', 'English', 'Logic'] The list after Update ['Programming', 'Mathematics', 'English']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-4
Search with
in, then remove by value.بە
inبگەڕێ، پاشان بە لای ببە.- Lineدێڕی 5-6
Not found:
pop()with no index removes the last element.نەدۆزرایەوە:
pop()بەبێ دوایین لادەبات.
Both branches remove one element, but in different ways: remove() by value, pop() by position. With a list that has no "Logic", the else branch runs:
هەردوو لقەکە یەک لادەبەن، بەڵام بە دوو ڕێگەی جیاواز: remove() بە و pop() بە شوێن. بە کە "Logic"ی تێدا نییە، بەشی else جێبەجێ دەبێت:
modules = ["Programming", "Mathematics", "English", "Physics"]
print("The list before Update ", modules)
if "Logic" in modules:
modules.remove("Logic")
else:
modules.pop()
print("The list after Update", modules)The list before Update ['Programming', 'Mathematics', 'English', 'Physics'] The list after Update ['Programming', 'Mathematics', 'English']
Joining lists with +پێکەوەلکاندنی لیستەکان بە +
Two lists can be joined with the + operator. This concatenation makes a new list holding the elements of the first list followed by the elements of the second. The two original lists do not change.
دوو بە + پێکەوە دەلکێنرێن. ئەم نوێ دروست دەکات کە یەکەم و لە دوایانەوە دووەم هەڵدەگرێت. دوو ڕەسەنەکە ناگۆڕێن.
my_fav_fruits = ["Orange", "Kiwi", "Fig"]
your_fav_fruits = ["Apple", "mango"]
our_fav_fruits = my_fav_fruits + your_fav_fruits
for i in our_fav_fruits:
print(i, end=" ")Orange Kiwi Fig Apple mango
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
A new list with five elements: three from the first list, then two from the second.
نوێ بە پێنج : سێ لە یەکەم، پاشان دوو لە دووەم.
- Lineدێڕی 5
end=" "prints two spaces instead of a new line.end=" "لەبری دێڕی نوێ دوو بۆشایی چاپ دەکات.
The slide named the lists myFavFruits, yourFavFruits and ourfavFruits; Python's style guide, PEP 8, prefers snake_case names such as my_fav_fruits. To change a list in place instead of making a new one, use += (the same as extend()).
سلایدەکە ناوی نابوو myFavFruits، yourFavFruits و ourfavFruits؛ ڕێبەری شێوازی ، PEP 8، ناوی snake_caseی وەک my_fav_fruitsی پێ باشترە. بۆ گۆڕینی لە شوێنی خۆیدا لەبری دروستکردنی نوێ، += بەکار بهێنە (وەک extend()).
+ لیستێکی نوێ دروست دەکات؛ += کۆنەکە دەگۆڕێتconcat_new.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەa = [1, 2]
b = [3, 4]
c = a + b
print(c)
print(a, b)
a += [5]
print(a)[1, 2, 3, 4] [1, 2] [3, 4] [1, 2, 5]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-5
aandbare untouched aftera + b.دوای
a + b،aوbدەستیان لێ نادرێت.- Lineدێڕی 6
a += [5]extendsaitself.a += [5]خودیaدرێژ دەکاتەوە.
Repeating a list with *دووبارەکردنەوەی لیستێک بە *
To join a list to itself several times, use the replication operator *: [1, 2, 3] * 4 is the list [1, 2, 3] four times in a row, 12 elements. A common use is to make a list of equal starting values, for example [0] * 5. Multiplying by 0 (or a negative number) gives an empty list.
بۆ لکاندنی بە خۆیەوە چەند جارێک، * بەکار بهێنە: [1, 2, 3] * 4 واتە [1, 2, 3] چوار جار لە دوای یەک، 12 . بەکارهێنانێکی باو دروستکردنی لە سەرەتایی یەکسان، بۆ نموونە [0] * 5. لێکدان لە 0 (یان ) بەتاڵ دەدات.
month_in_quarter = [1, 2, 3] * 4
print(month_in_quarter)
print(len(month_in_quarter))
print(month_in_quarter[5 - 1])
zeros = [0] * 5
print(zeros)
print(["Hi"] * 3)
print([1, 2] * 0)[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] 12 2 [0, 0, 0, 0, 0] ['Hi', 'Hi', 'Hi'] []
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The slide's name was
monthInQuarter; snake_case here.ناوی سلایدەکە
monthInQuarterبوو؛ لێرەدا snake_case.- Lineدێڕی 4
Month 5 (May) is at index 4: it is month 2 of its quarter.
مانگی 5 (ئایار) لە 4دایە: مانگی دووەمی چارەکەکەیەتی.
- Lineدێڕی 5
Five zeros: a quick way to prepare counters or scores.
پێنج سفر: ڕێگەیەکی خێرا بۆ ئامادەکردنی یان خاڵەکان.
- Lineدێڕی 8
Times 0: an empty list.
لێکدان لە 0: بەتاڵ.
Why is the slide's list called month in quarter? A year has four quarters of three months. For a month number m from 1 to 12, month_in_quarter[m - 1] tells whether it is the 1st, 2nd or 3rd month of its quarter: January → 1, May → 2, December → 3.
بۆچی سلایدەکە ناوی month in quarterـە؟ ساڵ چوار چارەکی سێ مانگی هەیە. بۆ ژمارەی مانگێک m لە 1 تا 12، month_in_quarter[m - 1] دەڵێت ئایا مانگی یەکەم، دووەم یان سێیەمی چارەکەکەیەتی: کانوونی دووەم ← 1، ئایار ← 2، کانوونی یەکەم ← 3.
Comparing lists with == and !=بەراوردکردنی لیستەکان بە == و !=
== checks whether two lists have the same elements in the same order. Python compares them pair by pair from index 0; as soon as one pair differs, the answer is False. != is the opposite of ==.
== دەپشکنێت ئایا دوو هەمان بە هەمان ڕیزیان هەیە. جووت بە جووت لە 0ەوە بەراوردیان دەکات؛ هەر کە جووتێک جیاواز بوو، وەڵامەکە Falseـە. != پێچەوانەی ==ـە.
print([1, 4, 9] == [1, 4, 9])
print([1, 4, 9] == [4, 1, 9])
print([1, 4, 9] != [4, 9])True False True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Same elements, same order:
True.هەمان ، هەمان ڕیز:
True.- Lineدێڕی 2
Same elements in a different order:
False.هەمان بە ڕیزێکی جیاواز:
False.- Lineدێڕی 3
Different lengths, so they are not equal:
!=givesTrue.درێژیی جیاواز، بۆیە یەکسان نین:
!=Trueدەدات.
print([1, 2] == [1.0, 2.0])
print([1, 2] == (1, 2))
print(["Erbil"] == ["erbil"])
print([] == [])True False False True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
1 == 1.0 and 2 == 2.0, so the lists are equal.
1 == 1.0 و 2 == 2.0، بۆیە یەکسانن.
- Lineدێڕی 2
A list never equals a tuple, even with the same items.
هەرگیز یەکسان نییە بە ، تەنانەت بە هەمان بڕگەش.
- Lineدێڕی 3
String comparison is case-sensitive.
بەراوردکردنی هەستیارە بە پیتی گەورە و بچووک.
Comparing lists with == and !=بەراوردکردنی لیستەکان بە == و !=
< and >: dictionary order for lists< و >: ڕیزبەندیی فەرهەنگی بۆ لیستەکان
<, >, <= and >= work on lists too, in lexicographic order, the order of a dictionary. Compare the first pair; if it is equal, the second pair; and so on. The first pair that differs decides. If one list runs out first while all pairs so far were equal, the shorter list is the smaller. Strings are compared by the same rule (see Comparing strings).
<، >، <= و >= لەسەر کار دەکەن، بە ، واتە ڕیزی فەرهەنگ. یەکەم جووت بەراورد بکە؛ ئەگەر یەکسان بوون، جووتی دووەم و بەم شێوەیە. یەکەم جووتی جیاواز بڕیار دەدات. ئەگەر زووتر تەواو بوو لە کاتێکدا هەموو جووتەکانی پێشوو یەکسان بوون، ئەو کورتترە بچووکترە. بە هەمان یاسا بەراورد دەکرێن (بڕوانە بەراوردکردنی زنجیرەنووسەکان).
print([1, 2, 3] < [1, 2, 4])
print([1, 2, 3, 4] < [1, 2, 4])
print([1, 2] < [1, 2, -1])
print([2] > [1, 100, 100])
print(["Aram", 17] < ["Aram", 19])
print(["Dilan", 90] < ["Aram", 95])True True True True True False
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
First difference: .
یەکەم جیاوازی: .
- Lineدێڕی 2
at index 2 decides; the extra 4 does not matter.
لە 2دا بڕیار دەدات؛ 4ـی زیادە گرنگ نییە.
- Lineدێڕی 3
[1, 2]is a beginning of[1, 2, -1], so it is smaller.[1, 2]سەرەتای[1, 2, -1]ـە، بۆیە بچووکترە.- Lineدێڕی 5-6
Rows such as [name, mark] are ordered by name first, then by mark.
ڕیزی وەک [ناو، نمرە] سەرەتا بە ناو و پاشان بە نمرە ڕیز دەکرێن.
This is how Python sorts a list of rows, such as [name, mark] pairs: by the first item, and by the second only when the first items are equal. You will use it in Processing two-dimensional lists. Elements that cannot be compared, such as a string and a number at the same position, give a TypeError.
بەم شێوەیە لە ڕیزەکان ڕیز دەکات، وەک جووتی [name, mark]: بە یەکەم بڕگە و تەنها کاتێک یەکەم بڕگەکان یەکسان بن بە دووەم. لە کارکردن لەگەڵ لیستە دووڕەهەندەکان بەکاری دەهێنیت. ئەگەر دوو بەراورد نەکرێن، وەک و ژمارەیەک لە هەمان شوێندا، TypeError دروست دەبێت.
print([1, "a"] < [1, 2])Traceback (most recent call last):
File "less_than_error.py", line 1, in <module>
print([1, "a"] < [1, 2])
^^^^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'str' and 'int'Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوودەدات | Fixچارەسەر |
|---|---|---|
fruits.remove(1) to remove index 1fruits.remove(1) بۆ لابردنی 1 | ValueError: it looks for the value 1ValueError: بەدوای 1دا دەگەڕێت | fruits.pop(1) |
fruits.pop('apple') | TypeError: pop needs an indexTypeError: pop پێویستە | fruits.remove('apple') |
a.remove(x) without checkinga.remove(x) بەبێ پشکنین | ValueError if x is missingئەگەر x نەبێت ValueError | if x in a: a.remove(x) |
a = a.remove(x) | a becomes Nonea دەبێتە None | a.remove(x) |
fruits - ['apple'] | TypeError: lists have no -TypeError: -ـی نییە | fruits.remove('apple') |
numbers + 3 | TypeError: + needs two listsTypeError: + دوو پێویستە | numbers + [3] or numbers.append(3)numbers + [3] یان numbers.append(3) |
| Removing from a list while looping over itلابردن لە لە کاتی سووڕانەوە بەسەریدا | Some elements are skippedهەندێک بازیان بەسەردا دەدرێت | Build a new list (next screen) نوێ دروست بکە (شاشەی داهاتوو) |
remove() نرخێک دەوێت، نەک ئیندێکسmistake_remove_index.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange', 'banana']
fruits.remove(1)Traceback (most recent call last):
File "mistake_remove_index.py", line 2, in <module>
fruits.remove(1)
ValueError: list.remove(x): x not in listpop() ئیندێکسێک دەوێت، نەک نرخmistake_pop_value.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange', 'banana']
fruits.pop('apple')Traceback (most recent call last):
File "mistake_pop_value.py", line 2, in <module>
fruits.pop('apple')
TypeError: 'str' object cannot be interpreted as an integerfruits = ['apple', 'orange', 'banana']
fruits = fruits - ['apple']Traceback (most recent call last):
File "mistake_minus.py", line 2, in <module>
fruits = fruits - ['apple']
~~~~~~~^~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'list' and 'list'+ تەنها دوو لیست پێکەوە دەلکێنێتconcat_error.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەnumbers = [1, 2]
numbers = numbers + 3Traceback (most recent call last):
File "concat_error.py", line 2, in <module>
numbers = numbers + 3
~~~~~~~~^~~
TypeError: can only concatenate list (not "int") to listCommon mistakesهەڵە باوەکان
Do not remove while you loop over the same listلە کاتی سووڕانەوە بەسەر هەمان لیستدا لای مەبە
This program tries to remove every even number. It leaves 4 behind. When 2 is removed, every element moves one place left, so 4 slides into the place the loop has already visited, and the loop goes on with 6. Removing 6 pulls 7 back in the same way, so the loop skips 7 (harmless here, it is odd) and still reaches and removes 8.
ئەم هەوڵ دەدات هەموو ژمارەیەکی جووت لاببات. 4 بەجێ دەهێڵێت. کاتێک 2 لادەبرێت، هەموو دوای ئەو یەک شوێن بەرەو چەپ دەجووڵێن، بۆیە 4 دەخزێتە ئەو شوێنەی کە پێشتر سەردانی کردووە و بە 6 بەردەوام دەبێت. لابردنی 6 بە هەمان شێوە 7 دەکێشێتەوە دواوە، بۆیە بازی بەسەر 7دا دەدات (لێرەدا زیانی نییە، چونکە تاکە) و هێشتا دەگاتە 8 و لای دەبات.
numbers = [2, 4, 6, 7, 8]
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers)[4, 7]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-4
Round 1 sees 2 and removes it; 4 moves to index 0, but round 2 looks at index 1, which is now 6.
لە یەکەمدا 2 دەبینرێت و لادەبرێت؛ 4 دەچێتە 0، بەڵام دووەم سەیری 1 دەکات، کە ئێستا 6ە.
numbers = [2, 4, 6, 7, 8]
odds = []
for n in numbers:
if n % 2 != 0:
odds.append(n)
print(odds)[7]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-5
Keep what you want instead of removing what you do not want.
ئەوەی دەتەوێت بیهێڵەرەوە لەبری لابردنی ئەوەی نایەوێت.
Exercisesڕاهێنانەکان
Without running it: what does this program print?
بەبێ جێبەجێکردن: ئەم چی چاپ دەکات؟
items = ["a", "b", "c", "d", "e", "b"]
items.pop(2)
items.remove("b")
del items[-1]
x = items.pop()
print(x, items)Show answerوەڵامەکە پیشان بدە
items = ["a", "b", "c", "d", "e", "b"]
items.pop(2)
items.remove("b")
del items[-1]
x = items.pop()
print(x, items)e ['a', 'd']
Step by step: pop(2) removes 'c' → ['a', 'b', 'd', 'e', 'b']; remove('b') removes the first 'b' → ['a', 'd', 'e', 'b']; del items[-1] removes the last 'b' → ['a', 'd', 'e']; pop() returns 'e' → ['a', 'd'].
هەنگاو بە هەنگاو: pop(2) 'c' لادەبات ← ['a', 'b', 'd', 'e', 'b']؛ remove('b') یەکەم 'b' لادەبات ← ['a', 'd', 'e', 'b']؛ del items[-1] دوایین 'b' لادەبات ← ['a', 'd', 'e']؛ pop() 'e' دەگەڕێنێتەوە ← ['a', 'd'].
Without running it: what are the four lines this program prints?
بەبێ جێبەجێکردن: ئەم چ چوار دێڕێک چاپ دەکات؟
a = [10, 20, 30, 40, 50, 60, 70, 80]
for i in range(0, len(a), 2):
print(a[i], end=" ")
print()
del a[::2]
print(a)
del a[2:]
print(a)
del a[:1]
print(a)Hintئاماژە
range(0, len(a), 2) gives the even indexes 0, 2, 4, 6. A slice in del works like the same slice when you read.
range(0, len(a), 2) جووتەکان دەدات: 0، 2، 4 و 6. لە ناو delـدا وەک هەمان لە کاتی خوێندنەوەدا کار دەکات.
Show answerوەڵامەکە پیشان بدە
a = [10, 20, 30, 40, 50, 60, 70, 80]
for i in range(0, len(a), 2):
print(a[i], end=" ")
print()
del a[::2]
print(a)
del a[2:]
print(a)
del a[:1]
print(a)10 30 50 70 [20, 40, 60, 80] [20, 40] [40]
The loop prints the elements at the even indexes. del a[::2] deletes exactly those elements (every second one, from index 0), so the odd-index ones are left. del a[2:] deletes from index 2 to the end, and del a[:1] deletes the first element.
ئەو چاپ دەکات کە لە جووتەکاندان. del a[::2] ڕێک هەمان لادەبات (یەک لە دووان، لە 0ەوە)، بۆیە ئەوانەی تاکە دەمێننەوە. del a[2:] لە 2ەوە تا کۆتایی لادەبات و del a[:1] یەکەم لادەبات.
remove() deletes only the first match. Remove every "k" from letters = ["k", "u", "r", "d", "k", "k"].
remove() تەنها یەکەم هاوتا دەسڕێتەوە. هەموو "k"ـێک لە letters = ["k", "u", "r", "d", "k", "k"] لاببە.
Hintئاماژە
while "k" in letters:
while "k" in letters:
Show answerوەڵامەکە پیشان بدە
letters = ["k", "u", "r", "d", "k", "k"]
while "k" in letters:
letters.remove("k")
print(letters)['u', 'r', 'd']
The while loop repeats as long as a "k" is left, so remove() never meets a missing value. (Building a new list, as on the mistakes screen, works too.)
تا ئەو کاتەی "k"ـێک لە هەبێت دووبارە دەبێتەوە، بۆیە remove() هەرگیز تووشی نابێت کە نییە. (دروستکردنی نوێ، وەک شاشەی هەڵەکان، کاریش دەکات.)
A text editor keeps the user's actions in a list. Append three actions, then undo the last one with pop() and print what was undone and what is left.
کارەکانی لە هەڵدەگرێت. سێ کار append بکە، پاشان بە pop() لە دوایینیان پاشگەز ببەرەوە و چاپ بکە چی هەڵوەشێنرایەوە و چی دەمێنێتەوە.
Show answerوەڵامەکە پیشان بدە
history = []
history.append("type A")
history.append("type B")
history.append("delete line")
print(history)
undone = history.pop()
print("Undo:", undone)
print(history)['type A', 'type B', 'delete line'] Undo: delete line ['type A', 'type B']
Adding at the end and taking from the end is how a stack works (last in, first out), taught fully in Stacks. The AI labs use exactly this: see A list as a stack or a queue.
زیادکردن لە کۆتاییدا و وەرگرتن لە کۆتاییەوە شێوەی کارکردنی (دوایین هاتوو، یەکەم دەرچوو)، کە بە تەواوی لە ستاکەکان فێری دەبیت. تاقیگەکانی ڕێک ئەمە بەکار دەهێنن: بڕوانە لیست وەک ستاک یان کیوو.
class_a = ["Aram", "Shilan", "Karwan"], class_b = ["Dilan", "Rezan"]. Make one list of everyone and print it with its length. Then test whether class_a equals ["Aram", "Shilan", "Karwan"] and whether it equals the same names in another order.
class_a = ["Aram", "Shilan", "Karwan"]، class_b = ["Dilan", "Rezan"]. یەک لە هەمووان دروست بکە و لەگەڵ درێژییەکەی چاپی بکە. پاشان تاقی بکەرەوە ئایا class_a یەکسانە بە ["Aram", "Shilan", "Karwan"] و ئایا یەکسانە بە هەمان ناوەکان بە ڕیزێکی تر.
Show answerوەڵامەکە پیشان بدە
class_a = ["Aram", "Shilan", "Karwan"]
class_b = ["Dilan", "Rezan"]
everyone = class_a + class_b
print(everyone, len(everyone))
print(class_a == ["Aram", "Shilan", "Karwan"])
print(class_a == ["Shilan", "Aram", "Karwan"])['Aram', 'Shilan', 'Karwan', 'Dilan', 'Rezan'] 5 True False
+ joins the classes into a new list; == is True only when the order matches too.
+ پۆلەکان دەکاتە نوێ؛ == تەنها کاتێک Trueـە کە ڕیزەکەش وەک یەک بێت.
Make a row of five seats that all say "empty" with one replication. Seat Hana in the middle seat and Soran in the last one, print the row and count the empty seats.
بە یەک دووبارەکردنەوە ڕیزێکی پێنج کورسی دروست بکە کە هەموویان "empty" بن. Hana لە کورسیی ناوەڕاست و Soran لە دوایین کورسی دابنێ، ڕیزەکە چاپ بکە و کورسییە بەتاڵەکان بژمێرە.
Hintئاماژە
["empty"] * 5
["empty"] * 5
Show answerوەڵامەکە پیشان بدە
seats = ["empty"] * 5
seats[2] = "Hana"
seats[-1] = "Soran"
print(seats)
print(seats.count("empty"))['empty', 'empty', 'Hana', 'empty', 'Soran'] 3
The middle of five seats is index 2, and the last is index -1. count() from the previous lesson counts the remaining "empty" strings.
ناوەڕاستی پێنج کورسی 2ە و دوایینیان -1. count() لە وانەی پێشووەوە دەژمێرێت چەند "empty" دەمێنێتەوە.
Write a program that keeps a list of whole numbers, starting with [5, 3, 8], and shows a menu again and again until the user chooses 0: 1 append a number, 2 insert a number at an index, 3 extend with several numbers typed on one line, 4 change the number at an index, 5 remove by index, 6 remove by value, 7 sort (ascending or descending), 8 show the list. A wrong index or a missing value must give a message, not a crash.
بنووسە کە لە هەڵدەگرێت، بە [5, 3, 8] دەست پێ دەکات و مێنیوێک دووبارە و دووبارە پیشان دەدات تا 0 هەڵدەبژێرێت: 1 ژمارەیەک append بکە، 2 ژمارەیەک لە insert بکە، 3 بە چەند ژمارەیەک کە لە یەک دێڕدا نووسراون extend بکە، 4 ژمارەی سەر بگۆڕە، 5 بە لاببە، 6 بە لاببە، 7 ڕیز بکە (بەرەو سەر یان بەرەو خوار)، 8 پیشان بدە. هەڵە یان کە نییە دەبێت پەیامێک بدات، نەک بوەستێنێت.
Hintئاماژە
Use while True: with break for 0, and compare the choice as text: choice == "1". Check an index with -len(numbers) <= i < len(numbers) and a value with in before you remove. sort() and sort(reverse=True) are explained in Sorting a list.
بۆ 0 while True: لەگەڵ break بەکار بهێنە و هەڵبژاردنەکە وەک دەق بەراورد بکە: choice == "1". پێش لابردن، بە -len(numbers) <= i < len(numbers) و بە in بپشکنە. sort() و sort(reverse=True) لە ڕیزکردنی لیستێک ڕوون کراونەتەوە.
Show answerوەڵامەکە پیشان بدە
numbers = [5, 3, 8]
while True:
print("1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit")
choice = input("Choice: ")
if choice == "1":
numbers.append(int(input("Number: ")))
elif choice == "2":
i = int(input("Index: "))
numbers.insert(i, int(input("Number: ")))
elif choice == "3":
new = []
for word in input("Numbers with spaces: ").split():
new.append(int(word))
numbers.extend(new)
elif choice == "4" or choice == "5":
i = int(input("Index: "))
if not (-len(numbers) <= i < len(numbers)):
print("No element has index", i)
elif choice == "4":
numbers[i] = int(input("New number: "))
else:
print("Removed", numbers.pop(i))
elif choice == "6":
value = int(input("Value: "))
if value in numbers:
numbers.remove(value)
else:
print(value, "is not in the list")
elif choice == "7":
order = input("a = ascending, d = descending: ")
numbers.sort(reverse=(order == "d"))
elif choice == "8":
print(numbers)
elif choice == "0":
break
else:
print("Unknown choice")
print("Final list:", numbers)1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 1 Number: 10 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 2 Index: 0 Number: 1 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 3 Numbers with spaces: 4 9 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 5 Index: 9 No element has index 9 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 5 Index: 1 Removed 5 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 6 Value: 42 42 is not in the list 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 7 a = ascending, d = descending: d 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 8 [10, 9, 8, 4, 3, 1] 1 append 2 insert 3 extend 4 change 5 pop 6 remove 7 sort 8 show 0 exit Choice: 0 Final list: [10, 9, 8, 4, 3, 1]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The menu repeats until
break.مێنیوەکە دووبارە دەبێتەوە تا
break.- Lineدێڕی 11-14
Collect the new numbers in a list, then
extend()adds them one by one.ژمارە نوێیەکان لە کۆ بکەرەوە، پاشان
extend()یەک یەک زیادیان دەکات.- Lineدێڕی 15-17
Options 4 and 5 both need a valid index, so they share the check.
هەڵبژاردنی 4 و 5 هەردووکیان دروستیان پێویستە، بۆیە پشکنینەکەیان هاوبەشە.
- Lineدێڕی 21-22
pop(i)returns what it removed, so the program can show it.pop(i)ئەوەی لایبردووە دەیگەڕێنێتەوە، بۆیە دەتوانێت پیشانی بدات.- Lineدێڕی 25-28
Test with
infirst:remove()of a missing value would stop the program.سەرەتا بە
inتاقی بکەرەوە:remove()ـی کە نییە دەوەستێنێت.
Every list tool of the last two lessons appears once: append(), insert(), extend(), changing by index, pop(), remove(), plus sort(). The checks before pop() and remove() turn crashes into messages. Typing a letter where a number is expected would still stop the program with ValueError; catching that is shown in A safe input function.
هەموو ئامرازەکانی لە دوو وانەی ڕابردوودا یەک جار دەردەکەون: append()، insert()، extend()، گۆڕین بە ، pop()، remove() و هەروەها sort(). پشکنینەکانی پێش pop() و remove() تێکچوون دەکەن بە پەیام. نووسینی پیتێک لە شوێنی ژمارەدا هێشتا بە ValueError دەوەستێنێت؛ چۆنیەتی گرتنی ئەوە لە کردارێکی نێوخستەی سەلامەت پیشان دراوە.
Summaryپوختە
pop(i)removes and returns the element at index i;pop()takes the last one. Bad index or empty list:IndexError.remove(x)removes the first element equal to x; if x is missing it raisesValueError, so testif x in a:first.del a[i]/del a[i:j]remove by position without returning anything;clear()empties the list.- After a removal the later elements move one place left; never remove from a list while looping over it.
a + bmakes a new list;a * nrepeats a list n times;+=changes the list in place.==is True for the same elements in the same order;<and>compare lists pair by pair in lexicographic order.
pop(i)i لادەبات و دەیگەڕێنێتەوە؛pop()دوایینیان دەبات. هەڵە یان بەتاڵ:IndexError.remove(x)یەکەم کە یەکسانە بە x لادەبات؛ ئەگەر x نەبێتValueErrorدروست دەکات، بۆیە سەرەتاif x in a:تاقی بکەرەوە.del a[i]/del a[i:j]بە شوێن لادەبەن بەبێ گەڕاندنەوەی هیچ؛clear()بەتاڵ دەکاتەوە.- دوای لابردن دواتر یەک شوێن بەرەو چەپ دەجووڵێن؛ هەرگیز لە کاتی سووڕانەوە بەسەر لێی لامەبە.
a + bنوێ دروست دەکات؛a * nn جار دووبارە دەکاتەوە؛+=لە شوێنی خۆیدا دەگۆڕێت.==بۆ هەمان بە هەمان ڕیز True ـە؛<و>جووت بە جووت بە بەراورد دەکەن.
What is the difference between a.pop(1) and a.remove(1)?جیاوازیی نێوان a.pop(1) و a.remove(1) چییە؟
pop(1) removes the element at index 1 and returns it; remove(1) removes the first element whose value is 1.
pop(1) 1 لادەبات و دەیگەڕێنێتەوە؛ remove(1) یەکەم لادەبات کە 1ە.
a = [1, 2]. Which of a + [3] and a += [3] changes a?a = [1, 2]. کامیان لە a + [3] و a += [3] a دەگۆڕێت؟
Only a += [3]; a + [3] builds a new list and leaves a alone.
تەنها a += [3]؛ a + [3] نوێ دروست دەکات و a بەجێ دەهێڵێت.
Is [3, 1] < [3, 1, 0] True or False? Why?[3, 1] < [3, 1, 0] True ـە یان False؟ بۆچی؟
True: all pairs are equal until the shorter list ends, and the shorter list is the smaller.
True: هەموو جووتەکان یەکسانن تا ئەو کورتترە تەواو دەبێت و ئەو کورتترە بچووکترە.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Lists, References, Copies and Functionsلیستەکان، ئاماژەکان، کۆپی و کردارەکان
Related lecturesوانە پەیوەندیدارەکان
- Lists: Creating and Indexingلیستەکان: دروستکردن و ئیندێکسەکان
- Lists, References, Copies and Functionsلیستەکان، ئاماژەکان، کۆپی و کردارەکان
- Processing Two-Dimensional Listsکارکردن لەسەر لیستە دووڕەهەندەکان
- Working with Stringsکارکردن لەگەڵ زنجیرەنووسەکان
- The Python You Need for the AI Labsئەو Pythonـەی بۆ تاقیگەکانی ژیریی دەستکرد پێویستە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- The Python Tutorial, 5.1 More on Lists (pop, remove, clear) and 5.2 The del statement
- The Python Tutorial, 5.8 Comparing Sequences and Other Types
- Python Standard Library: Built-in Types — common and mutable sequence operations
- Python Language Reference: Value comparisons
- PEP 8 — Style Guide for Python Code (naming conventions)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.