PythonPython · Chapterبەش 9 · Lectureوانە 9.2
Adding to a List and Finding Itemsزیادکردن بۆ لیستێک و دۆزینەوەی دانەکان
The four ways to put elements into a list (start values, append, insert, extend), filling a list from the keyboard, testing membership with in and not in, finding positions with index() and count(), and Lab 3 Tasks 1-2 and 1-3 and Lab 4 Tasks 1-1 and 1-2 with their slide errors corrected.
چوار ڕێگەی دانانی لە ( سەرەتا، append، insert و extend)، پڕکردنەوەی لە کیبۆردەوە، تاقیکردنەوەی ئەندامێتی بە in و not in، دۆزینەوەی شوێن بە index() و count()، لەگەڵ ئەرکەکانی 1-2 و 1-3ی تاقیگەی 3 و ئەرکەکانی 1-1 و 1-2ی تاقیگەی 4 بە ڕاستکراوەی هەڵەکانی سلایدەکان.
What you will learnچی فێر دەبیت
- Add elements with
append(),insert()andextend(), and choose the right one. - Predict where
insert()puts an element for any index, including negative and too-large ones. - Fill a list from user input safely with
int(input()). - Test membership with
in/not inand find positions withindex()andcount()without crashing.
- بە
append()،insert()وextend()زیاد بکەیت و دروستەکەیان هەڵبژێریت. - پێشبینی بکەیت
insert()لە کوێ دادەنێت بۆ هەر ، سالب و زۆر گەورەشەوە. - لە بە سەلامەتی بە
int(input())پڕ بکەیتەوە. - ئەندامێتی بە
in/not inتاقی بکەیتەوە و شوێن بەindex()وcount()بدۆزیتەوە بەبێ تێکچوون.
Four ways to put elements into a listچوار ڕێگە بۆ دانانی دانەکان لە لیستێکدا
A list can get its elements in four ways. You can write them when you create the list, append one at the end, insert one at a chosen index, or extend the list with several elements at once. All four lines below end with the same list, [2, 4].
بە چوار ڕێگە وەردەگرێت. دەتوانیت لە کاتی دروستکردنی بیاننووسیت، یەکێک بە append بخەیتە کۆتایی، یەکێک بە insert لە هەڵبژێردراودا دابنێیت یان بە extend چەند بە یەکجار زیاد بکەیت. هەر چوار ڕێگەکەی خوارەوە بە هەمان کۆتایی دێن، [2, 4].
mylist = [2, 4] # 1. start with the values
print(mylist)
mylist = list([2, 4]) # the same with list()
print(mylist)
mylist = [] # 2. append: add at the end
mylist.append(2)
mylist.append(4)
print(mylist)
mylist = [] # 3. insert: add at an index
mylist.insert(1, 4)
mylist.insert(0, 2)
print(mylist)
mylist = [2] # 4. extend: add several at once
mylist.extend([4])
print(mylist)[2, 4] [2, 4] [2, 4] [2, 4] [2, 4]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-4
Write the elements directly, or pass a list to
list().ڕاستەوخۆ بنووسە، یان بدە بە
list().- Lineدێڕی 6-9
Start empty and append twice.
بە بەتاڵی دەست پێ بکە و دوو جار append بکە.
- Lineدێڕی 11-14
insert(1, 4)on an empty list just puts 4 in; theninsert(0, 2)puts 2 in front.insert(1, 4)لەسەر بەتاڵ تەنها 4 دادەنێت؛ پاشانinsert(0, 2)2 دەخاتە پێشەوە.- Lineدێڕی 16-17
extend()adds every element of another list.extend()هەموو تر زیاد دەکات.
append, insert and extend are methods: functions that belong to the list. You call them with a dot after the list's name, fruits.append('kiwi'). They change the list in place and give back nothing (None).
append، insert و extend : کە هی . بە خاڵێک لە دوای ناوی بانگیان دەکەیت، fruits.append('kiwi'). لە شوێنی خۆیدا دەگۆڕن و هیچ شتێک ناگەڕێننەوە (None).
append(): add at the endappend(): زیادکردن لە کۆتاییدا
append() adds one new element to the end of the list. The syntax is list_name.append(new_element). If the order of the elements does not matter, for example a bag of names or a list of marks to add up later, appending is all you need.
append() یەک نوێ دەخاتە کۆتایی . شێوەی نووسینەکەی list_name.append(new_element)ـە. ئەگەر ڕیزی گرنگ نەبێت، بۆ نموونە کۆمەڵێک ناو یان لە نمرەکان کە دواتر کۆیان دەکەیتەوە، append هەموو ئەوەیە کە پێویستە.
fruits = ['apple', 'orange', 'banana']
fruits.append('kiwi')
for i in fruits:
print(i)apple orange banana kiwi
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
'kiwi' goes after 'banana', at index 3.
'kiwi' دەچێتە دوای 'banana'، لە 3.
- Lineدێڕی 3-4
The loop variable
iholds a fruit here, not an index;fruitwould be a clearer name.لێرەدا
iمیوەیەک هەڵدەگرێت، نەک ؛fruitناوێکی ڕوونترە.
append() changes the list itself and returns None. So use it as a statement on its own line; do not store its result.
append() خودی دەگۆڕێت و None دەگەڕێنێتەوە. بۆیە وەک لە دێڕێکی سەربەخۆدا بەکاری بهێنە؛ ئەنجامەکەی هەڵمەگرە.
append() چی دەگەڕێنێتەوەappend_none.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange']
result = fruits.append('kiwi')
print(result)
print(fruits)None ['apple', 'orange', 'kiwi']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The list changes, but
resultgetsNone.دەگۆڕێت، بەڵام
resultNoneوەردەگرێت.
insert(): add at a chosen positioninsert(): زیادکردن لە شوێنێکی دیاریکراودا
When the order matters and the new element must go to a particular position, use insert(): list_name.insert(index, new_element). Every element at that index and after it moves one place to the right to make room, the new element goes into the gap, and the list grows by 1.
کاتێک ڕیزەکە گرنگە و نوێ دەبێت بچێتە شوێنێکی دیاریکراو، insert() بەکار بهێنە: list_name.insert(index, new_element). هەموو لەو و دوای ئەو یەک شوێن بەرەو ڕاست دەجووڵێت بۆ ئەوەی جێگە بکاتەوە، نوێ دەچێتە بۆشاییەکەوە و 1 گەورەتر دەبێت.
fruits = ['apple', 'orange', 'banana']
fruits.insert(1, 'kiwi')
for i in fruits:
print(i)apple kiwi orange banana
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
'orange' and 'banana' move from indexes 1 and 2 to 2 and 3.
'orange' و 'banana' لە 1 و 2ەوە دەچنە 2 و 3.
![Animation of three lines of code. fruits = ['apple', 'orange', 'banana'] shows three boxes at indexes 0 to 2, len(fruits) = 3. fruits.append('kiwi') adds a highlighted 'kiwi' box at index 3; nothing else moves; len is 4. fruits.insert(1, 'fig'): the boxes 'orange', 'banana' and 'kiwi' slide one place to the right, to indexes 2, 3 and 4, leaving a dashed gap at index 1, and a 'fig' box waits above it. Then 'fig' drops into the gap; len is 5. The last frame highlights 'orange': it was at index 1 and is now at index 2.](/_astro/py-adding-and-finding-list-items-insert.en.DmANJfaJ.gif)
![Animation of three lines of code. fruits = ['apple', 'orange', 'banana'] shows three boxes at indexes 0 to 2, len(fruits) = 3. fruits.append('kiwi') adds a highlighted 'kiwi' box at index 3; nothing else moves; len is 4. fruits.insert(1, 'fig'): the boxes 'orange', 'banana' and 'kiwi' slide one place to the right, to indexes 2, 3 and 4, leaving a dashed gap at index 1, and a 'fig' box waits above it. Then 'fig' drops into the gap; len is 5. The last frame highlights 'orange': it was at index 1 and is now at index 2.](/_astro/py-adding-and-finding-list-items-insert.ckb.PqxJX77s.gif)
append() تەنها دەست لە کۆتایی دەدات؛ insert() دواتر یەک شوێن پاڵ دەنێت.CêITinsert(): add at a chosen positioninsert(): زیادکردن لە شوێنێکی دیاریکراودا
insert() accepts any indexinsert() هەر ئیندێکسێک وەردەگرێت
The slide says the index for insert() must be between 0 and the number of elements. That is good practice, but Python does not enforce it. An index past the end simply appends; a negative index counts from the end, so insert(-1, x) puts x before the last element; and insert(len(a), x) is exactly append(x). Even an empty list accepts insert(1, 4).
سلایدەکە دەڵێت insert() دەبێت لە نێوان 0 و ژمارەی بێت. ئەمە ڕاهێنانێکی باشە، بەڵام ناچاری ناکات. لە دوای کۆتاییەوە تەنها append دەکات؛ لە کۆتاییەوە دەژمێرێت، بۆیە insert(-1, x) x دەخاتە پێش دوایین ؛ و insert(len(a), x) ڕێک وەک append(x)ـە. تەنانەت بەتاڵیش insert(1, 4) وەردەگرێت.
fruits = ['apple', 'kiwi', 'orange', 'banana']
fruits.insert(100, 'fig')
print(fruits)
fruits.insert(-1, 'plum')
print(fruits)
fruits.insert(len(fruits), 'pear')
print(fruits)['apple', 'kiwi', 'orange', 'banana', 'fig'] ['apple', 'kiwi', 'orange', 'banana', 'plum', 'fig'] ['apple', 'kiwi', 'orange', 'banana', 'plum', 'fig', 'pear']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
100 is far past the end: 'fig' is simply appended.
100 زۆر لە دوای کۆتاییەوەیە: 'fig' تەنها append دەکرێت.
- Lineدێڕی 4
-1means "before the last element": 'plum' lands before 'fig'.-1واتە «پێش دوایین »: 'plum' دەکەوێتە پێش 'fig'.- Lineدێڕی 6
insert(len(fruits), x)is the same asappend(x).insert(len(fruits), x)وەکappend(x)ـە.
insert() لەسەر لیستێکی بەتاڵinsert_empty.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەmylist = []
mylist.insert(1, 4)
print(mylist)
mylist.insert(0, 2)
print(mylist)[4] [2, 4]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Index 1 is past the end of an empty list, so 4 becomes its only element.
1 لە دوای کۆتایی بەتاڵەوەیە، بۆیە 4 دەبێتە تاکە .
extend(): add several elements at onceextend(): زیادکردنی چەند دانەیەک بە یەکجار
extend() adds all the elements of another list to the end, one after the other. You can pass a list variable or write the new elements directly in square brackets. The list you pass in is not changed.
extend() هەموو تر یەک لە دوای یەک دەخاتە کۆتایی. دەتوانیت بدەیت یان نوێ ڕاستەوخۆ لە ناو کەوانەی چوارگۆشەدا بنووسیت. ئەو دەیدەیت ناگۆڕێت.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
list1 = ["a", "b", "c"]
list1.extend([1, 2, 3])
print(list1)['a', 'b', 'c', 1, 2, 3] ['a', 'b', 'c', 1, 2, 3]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
list2is passed in; its three elements are added tolist1.list2دەدرێت؛ سێ بۆlist1زیاد دەکرێن.- Lineدێڕی 7
The same with the elements written directly.
هەمان شت بە ڕاستەوخۆ نووسراو.
extend(): add several elements at onceextend(): زیادکردنی چەند دانەیەک بە یەکجار
append() or extend()?append() یان extend()؟
The two are easy to mix up. append() always adds exactly one element, whatever you give it; give it a list and that whole list becomes one element, a list inside the list. extend() takes a sequence and adds its items one by one. The augmented assignment a += [1, 2] does the same as a.extend([1, 2]).
ئەم دووانە ئاسان تێکەڵ دەکرێن. append() هەمیشە ڕێک یەک زیاد دەکات، هەرچییەکی پێ بدەیت؛ بدە پێی و هەموو ئەو دەبێتە یەک ، لە ناو . extend() وەردەگرێت و بڕگەکانی یەک یەک زیاد دەکات. a += [1, 2] هەمان کاری a.extend([1, 2]) دەکات.
a = ["a", "b"]
a.append([1, 2])
print(a, len(a))
b = ["a", "b"]
b.extend([1, 2])
print(b, len(b))
c = ["a", "b"]
c.extend("hi")
print(c)
d = ["a", "b"]
d += [1, 2]
print(d)['a', 'b', [1, 2]] 3 ['a', 'b', 1, 2] 4 ['a', 'b', 'h', 'i'] ['a', 'b', 1, 2]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
One element is added: the list
[1, 2].یەک زیاد دەکرێت:
[1, 2].- Lineدێڕی 10
A string is a sequence too:
extend("hi")adds'h'and'i'.:
extend("hi")'h'و'i'زیاد دەکات.- Lineدێڕی 14
+=with a list works likeextend().+=لەگەڵ وەکextend()کار دەکات.
Filling a list from the keyboardپڕکردنەوەی لیستێک لە کیبۆردەوە
Start with an empty list and append each value the user types. A for loop with range(3) asks three times. input() always gives text, so turn it into a number with int() before appending.
بە بەتاڵ دەست پێ بکە و هەر کە دەینووسێت append بکە. بە range(3) سێ جار دەپرسێت. input() هەمیشە دەق دەدات، بۆیە پێش append بە int() بیکە بە ژمارە.
mylist = []
for i in range(3):
mylist.append(int(input("enter list elements : ")))
print(mylist)enter list elements : 2 enter list elements : 4 enter list elements : 9 [2, 4, 9]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Read, convert and append in one line.
خوێندنەوە، گۆڕین و append لە یەک دێڕدا.
Is it in the list? The in operatorئایا لە لیستەکەدایە؟ کارپێکەری in
The in operator tests whether a value is contained in a list. It is a membership operator: the answer is True or False, so it fits straight into an if. not in asks the opposite.
in تاقی دەکاتەوە کە ئایا لە ناو . : وەڵامەکە True یان Falseـە، بۆیە ڕاستەوخۆ دەچێتە ناو ifـەوە. not in پێچەوانەکەی دەپرسێت.
fruits = ['apple', 'orange', 'banana']
if 'orange' in fruits:
print("orange is present in the list")
else:
print("orange is not in the list")orange is present in the list
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
'orange' in fruitsisTrue, so the first message is printed.'orange' in fruitsTrueـە، بۆیە یەکەم پەیام چاپ دەکرێت.
fruits = ['apple', 'orange', 'banana']
print('kiwi' in fruits)
print('kiwi' not in fruits)
print('Orange' in fruits)
print('app' in fruits)
print('app' in 'apple')False True False False True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
Case matters: 'Orange' is not 'orange'.
پیتی گەورە و بچووک گرنگە: 'Orange' یەکسان نییە بە 'orange'.
- Lineدێڕی 5-6
On a list,
inlooks for a whole element; on a string it looks for a piece of text.لەسەر ،
inبەدوای تەواودا دەگەڕێت؛ لەسەر بەدوای پارچە دەقێکدا.
Is it in the list? The in operatorئایا لە لیستەکەدایە؟ کارپێکەری in
How in searches: one element at a timein چۆن دەگەڕێت: یەک دانە لە هەر جارێکدا
To answer x in a, Python compares x with the elements one by one, starting at index 0, and stops at the first one that is equal. If none is equal, it has checked every element before it says False. This way of searching is called a linear search. Its best case is 1 comparison: x is the first element. Its worst case is comparisons for a list of elements: x is the last element, or not there at all.
بۆ وەڵامدانەوەی x in a، x لەگەڵ یەک یەک بەراورد دەکات، لە 0ەوە و لە یەکەم کە یەکسان بێت دەوەستێت. ئەگەر هیچیان یەکسان نەبوو، پێش ئەوەی بڵێت False هەموو پشکنیوە. بەم شێوەی گەڕانە دەوترێت . لە تەنها یەک بەراورد پێویستە: x یەکەم . لە ، بۆ بە ، بەراورد پێویستە: x دوایین ، یان هەر لە نییە.
![Animation with fruits = ['apple', 'orange', 'banana', 'kiwi']. For 'banana' in fruits, a pointer moves under the boxes: 'apple' == 'banana' → False, 'orange' == 'banana' → False, both boxes marked with a cross; 'banana' == 'banana' → True, the box is marked with a tick and the answer True appears: the search stops and 'kiwi' is never checked. Then 'fig' in fruits: all four boxes are crossed out, 4 comparisons and no match, and the answer is False.](/_astro/py-adding-and-finding-list-items-in-scan.en.ClBpTI8z.gif)
![Animation with fruits = ['apple', 'orange', 'banana', 'kiwi']. For 'banana' in fruits, a pointer moves under the boxes: 'apple' == 'banana' → False, 'orange' == 'banana' → False, both boxes marked with a cross; 'banana' == 'banana' → True, the box is marked with a tick and the answer True appears: the search stops and 'kiwi' is never checked. Then 'fig' in fruits: all four boxes are crossed out, 4 comparisons and no match, and the answer is False.](/_astro/py-adding-and-finding-list-items-in-scan.ckb.QV2bXFO_.gif)
fruits = ['apple', 'orange', 'banana', 'kiwi']
target = 'banana'
found = False
for fruit in fruits:
print("checking", fruit)
if fruit == target:
found = True
break
print(found)
print(target in fruits)checking apple checking orange checking banana True True
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4-8
Check each element;
breakstops at the first match, likein.هەر بپشکنە؛
breakلە یەکەم هاوتادا دەوەستێت، وەکin.- Lineدێڕی 10
One short expression does all of that.
یەک کورت هەموو ئەوانە دەکات.
Where is it? index()لە کوێیە؟ index()
Often you want to know where an element is. The index() method returns the index of the first match. In the list below 'orange' appears twice, at indexes 1 and 3, and index() gives 1.
زۆرجار دەتەوێت بزانیت لە کوێیە. index() یەکەم هاوتا دەگەڕێنێتەوە. لە خوارەوەدا 'orange' دوو جار هاتووە، لە 1 و 3دا و index() 1 دەدات.
fruits = ['apple', 'orange', 'banana', 'orange']
fav_fruit = fruits.index('orange')
print(fav_fruit)1
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The slide wrote
fruits.index('orange',); the extra comma is legal but useless.سلایدەکە
fruits.index('orange',)ی نووسیبوو؛ کۆما زیادەکە یاساییە بەڵام بێسوودە.
Making lists and reaching, changing and slicing their elements by index; later chapters remove elements and find where a value is.
دروستکردنی ، خوێندنەوە، گۆڕین و بە ؛ بەشەکانی دواتر لادەبەن و شوێنی دەدۆزنەوە.
Watch from 16:56: index(), checking with in first, and count().
لە 16:56 بەدواوە سەیر بکە: index()، سەرەتا پشکنین بە in و count().
Where is it? index()لە کوێیە؟ index()
When the value is missingکاتێک نرخەکە بوونی نییە
If the value is not in the list, index() does not return -1 or None: it raises a ValueError and the program stops. So check with in first, and only then ask for the index.
ئەگەر لە نەبێت، index() -1 یان None ناگەڕێنێتەوە: ValueError دروست دەکات و دەوەستێت. بۆیە سەرەتا بە in بپشکنە و ئینجا داوای بکە.
fruits = ['apple', 'orange', 'banana', 'orange']
print(fruits.index('kiwi'))Traceback (most recent call last):
File "index_missing.py", line 2, in <module>
print(fruits.index('kiwi'))
^^^^^^^^^^^^^^^^^^^^
ValueError: 'kiwi' is not in listfruits = ['apple', 'orange', 'banana', 'orange']
for name in ['banana', 'kiwi']:
if name in fruits:
print(name, "is at index", fruits.index(name))
else:
print(name, "is not in the list")banana is at index 2 kiwi is not in the list
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Only call
index()wheninhas saidTrue.تەنها کاتێک
index()بانگ بکە کەinگوتوویەتیTrue.
Where is it? index()لە کوێیە؟ index()
count(), and searching from a later indexcount() و گەڕان لە ئیندێکسێکی دواترەوە
Two more tools. count(x) tells how many times x appears; for a missing value it simply returns 0, with no error. And index(x, start) begins the search at index start, which finds the next match after a known one. The returned index is still counted from the start of the list.
دوو ئامرازی تر. count(x) دەڵێت x چەند جار هاتووە؛ بۆ کە بوونی نییە تەنها 0 دەگەڕێنێتەوە، بەبێ . هەروەها index(x, start) گەڕانەکە لە startـەوە دەست پێ دەکات، کە هاوتای داهاتوو دوای هاوتایەکی ناسراو دەدۆزێتەوە. ئەو دەگەڕێتەوە هێشتا لە سەرەتای دەژمێردرێت.
index() بە سەرەتایەک و count()index_start_count.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange', 'banana', 'orange']
print(fruits.index('orange'))
print(fruits.index('orange', 2))
print(fruits.count('orange'))
print(fruits.count('kiwi'))1 3 2 0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Start looking at index 2: the next 'orange' is at index 3.
لە 2ەوە بگەڕێ: 'orange'ـی داهاتوو لە 3دایە.
- Lineدێڕی 4-5
'orange' appears twice; 'kiwi' 0 times, without an error.
'orange' دوو جار هاتووە؛ 'kiwi' 0 جار، بەبێ .
Lab 3: adding to a list of numbersتاقیگەی 3: زیادکردن بۆ لیستێک لە ژمارەکان
Lab 3 starts (Task 1-1) with the ten numbers 2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43 and 38.2 and prints their sum, 1296.3, and their average, 129.63. That task is solved in sum, max, min and sorting. The next two tasks add one element and print the new sum and average. Here sum(numbers) adds up the list and len(numbers) counts it.
تاقیگەی 3 (ئەرکی 1-1) بە دە ژمارەی 2.7، 32، 768، 89.1، 21، 90.3، 135، 77، 43 و 38.2 دەست پێ دەکات و کۆکەیان، 1296.3 و تێکڕاکەیان، 129.63، چاپ دەکات. ئەو ئەرکە لە sum، max، min و ڕیزکردن چارەسەر کراوە. دوو ئەرکەکەی داهاتوو یەک زیاد دەکەن و کۆ و تێکڕای نوێ چاپ دەکەن. لێرەدا sum(numbers) کۆ دەکاتەوە و len(numbers) دەیژمێرێت.
Lab 3: adding to a list of numbersتاقیگەی 3: زیادکردن بۆ لیستێک لە ژمارەکان
Task 1-2: append 255ئەرکی 1-2: زیادکردنی 255
Start from numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]. Add a new element, 255, at the last position of the list. Print the list before and after the update, the new element, the sum and the average.
لە numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]ـەوە دەست پێ بکە. نوێ، 255، لە دوایین شوێنی زیاد بکە. پێش و دوای نوێکردنەوە، نوێ، کۆ و تێکڕا چاپ بکە.
Hintئاماژە
append() adds at the end; len() counts the elements after the update.
append() دەیخاتە کۆتایی؛ len() دوای نوێکردنەوە دەژمێرێت.
Show answerوەڵامەکە پیشان بدە
numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]
print("**The list before update", numbers)
new_element = 255
numbers.append(new_element)
print("new element is ", new_element)
print("**The list after update : ", numbers)
total = sum(numbers)
print("Sum is ", round(total, 2))
print("Average is ", round(total / len(numbers), 2))**The list before update [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2] new element is 255 **The list after update : [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2, 255] Sum is 1551.3 Average is 141.03
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
"At the last position" means
append().«لە دوایین شوێندا» واتە
append().- Lineدێڕی 9
Divide by
len(numbers), now 11, never by a fixed 10.round(…, 2)keeps two decimals.دابەشی
len(numbers)بکە، کە ئێستا 11ە، هەرگیز دابەشی 10ی جێگیر مەکە.round(…, 2)دوو ژمارەی دوای خاڵ دەهێڵێتەوە.
Lab 3: adding to a list of numbersتاقیگەی 3: زیادکردن بۆ لیستێک لە ژمارەکان
Task 1-3: insert 340.2 at the 5th positionئەرکی 1-3: دانانی 340.2 لە شوێنی پێنجەمدا
Start again from numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]. Add the new element 340.2 at the 5th position of the list, then print as in Task 1-2.
دیسان لە numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]ـەوە دەست پێ بکە. نوێی 340.2 لە شوێنی پێنجەمی دابنێ، پاشان وەک ئەرکی 1-2 چاپ بکە.
Hintئاماژە
Position 5 for a person is index 4 for Python.
شوێنی 5 بۆ مرۆڤ 4ە بۆ .
Show answerوەڵامەکە پیشان بدە
numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]
print("**The list before update", numbers)
new_element = 340.2
numbers.insert(4, new_element) # the 5th position is index 4
print("new element is ", new_element)
print("**The list after update : ", numbers)
total = sum(numbers)
print("Sum is ", round(total, 2))
print("Average is ", round(total / len(numbers), 2))**The list before update [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2] new element is 340.2 **The list after update : [2.7, 32, 768, 89.1, 340.2, 21, 90.3, 135, 77, 43, 38.2] Sum is 1636.5 Average is 148.77
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
The 5th position is index 4, because indexes start at 0.
شوێنی پێنجەم 4ە، چونکە لە 0ەوە دەست پێ دەکەن.
340.2 now stands after 89.1 (the 4th number) and pushes 21 and everything after it one place right. The sum is 1636.5 and, with 11 numbers, the average is .
340.2 ئێستا لە دوای 89.1 (ژمارەی چوارەم) وەستاوە و 21 و هەموو ئەوانەی دوای ئەو یەک شوێن بەرەو ڕاست پاڵ دەنێت. کۆکە 1636.5 دەبێت و بە 11 ژمارە، تێکڕاکە دەبێت.
Lab 4: filling a list until it is fullتاقیگەی 4: پڕکردنەوەی لیستێک تا پڕ دەبێت
Lab 4 begins with mylist = [111, 222, 555] and keeps asking the user for characters until the list holds ten elements. A while loop fits, because nobody knows in advance how many inputs that will take: its condition is len(mylist) < 10.
تاقیگەی 4 بە mylist = [111, 222, 555] دەست پێ دەکات و بەردەوام داوای لە دەکات تا دە هەڵدەگرێت. گونجاوە، چونکە کەس پێشتر نازانێت ئەوە چەند دەخایەنێت: len(mylist) < 10ـە.
Lab 4: filling a list until it is fullتاقیگەی 4: پڕکردنەوەی لیستێک تا پڕ دەبێت
Task 1-1: add characters until there are ten elementsئەرکی 1-1: زیادکردنی نووسەکان تا دە دانە هەبێت
Start with mylist = [111, 222, 555]. Print the list, then read characters from the user and append them until the list contains ten elements. Then print the list again.
بە mylist = [111, 222, 555] دەست پێ بکە. چاپ بکە، پاشان لە بخوێنەوە و بە append زیادیان بکە تا دە تێدا دەبێت. پاشان دیسان چاپ بکە.
Hintئاماژە
while len(mylist) < 10:
while len(mylist) < 10:
Show answerوەڵامەکە پیشان بدە
mylist = [111, 222, 555]
print("My list before inserting any character is :", mylist)
while len(mylist) < 10:
ch = input("Enter a character to a list : ")
mylist.append(ch)
print("My list after inserting character(s) is :", mylist)My list before inserting any character is : [111, 222, 555] Enter a character to a list : e Enter a character to a list : h Enter a character to a list : f Enter a character to a list : f Enter a character to a list : h Enter a character to a list : e Enter a character to a list : k My list after inserting character(s) is : [111, 222, 555, 'e', 'h', 'f', 'f', 'h', 'e', 'k']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
The loop runs while there are fewer than 10 elements: here 7 times.
تا ئەو کاتەی کەمتر لە 10 هەیە کار دەکات: لێرەدا 7 جار.
- Lineدێڕی 5
Each character goes to the end.
هەر دەچێتە کۆتایی.
Lab 4: filling a list until it is fullتاقیگەی 4: پڕکردنەوەی لیستێک تا پڕ دەبێت
Task 1-2: no duplicate charactersئەرکی 1-2: بێ نووسەیەکی دووبارە
Change Task 1-1 so that a character is added only if it is not already in the list. The list must again reach ten elements, now without duplicates.
ئەرکی 1-1 بگۆڕە بۆ ئەوەی تەنها کاتێک زیاد بکرێت کە پێشتر لە نەبێت. دەبێت دیسان بگاتە دە ، ئەمجارە بێ دووبارە.
Hintئاماژە
Wrap the append() in if ch not in mylist:.
append() بخە ناو if ch not in mylist:ـەوە.
Show answerوەڵامەکە پیشان بدە
mylist = [111, 222, 555]
print("My list before inserting any character is :", mylist)
while len(mylist) < 10:
ch = input("Enter a character to a list : ")
if ch not in mylist:
mylist.append(ch)
print("My list after inserting character(s) is :", mylist)My list before inserting any character is : [111, 222, 555] Enter a character to a list : w Enter a character to a list : g Enter a character to a list : s Enter a character to a list : w Enter a character to a list : s Enter a character to a list : g Enter a character to a list : t Enter a character to a list : s Enter a character to a list : s Enter a character to a list : r Enter a character to a list : w Enter a character to a list : r Enter a character to a list : d Enter a character to a list : s Enter a character to a list : t Enter a character to a list : v My list after inserting character(s) is : [111, 222, 555, 'w', 'g', 's', 't', 'r', 'd', 'v']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-6
not inlets only new characters through; repeated ones are skipped.not inتەنها ڕێگە بە نوێ دەدات؛ دووبارەکان پشتگوێ دەخرێن.
Sixteen inputs were needed: nine of them (w, s, g, s, s, w, r, s, t) were already in the list and were skipped.
شازدە پێویست بوو: نۆیان (w، s، g، s، s، w، r، s، t) پێشتر لە بوون و پشتگوێ خران.
The silent version is what the lab shows. A friendlier program tells the user why a character was not added:
وەشانە بێدەنگەکە ئەوەیە کە تاقیگەکە پیشانی دەدات. دۆستانەتر بە دەڵێت بۆچی زیاد نەکرا:
mylist = [111, 222, 555]
while len(mylist) < 10:
ch = input("Enter a character to a list : ")
if ch in mylist:
print(ch, "is already in the list")
else:
mylist.append(ch)
print(mylist)Enter a character to a list : w Enter a character to a list : g Enter a character to a list : w w is already in the list Enter a character to a list : s Enter a character to a list : t Enter a character to a list : r Enter a character to a list : d Enter a character to a list : v [111, 222, 555, 'w', 'g', 's', 't', 'r', 'd', 'v']
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-4
inandnot inare two sides of the same test.inوnot inدوو ڕووی هەمان تاقیکردنەوەن.
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوودەدات | Fixچارەسەر |
|---|---|---|
fruits = fruits.append('kiwi') | fruits becomes None; the next append failsfruits دەبێتە None؛ append ـی داهاتوو سەرناکەوێت | fruits.append('kiwi') |
fruits.append('kiwi', 'fig') | TypeError: append takes exactly one argumentTypeError: append تەنها یەک وەردەگرێت | fruits.extend(['kiwi', 'fig']) |
fruits.add('kiwi') | AttributeError: lists have no addAttributeError: addـی نییە | fruits.append('kiwi') |
a.append([1, 2]) to add two numbers | One nested element [1, 2] is addedیەک ناوەکی [1, 2] زیاد دەکرێت | a.extend([1, 2]) |
insert(5, x) for "the 5th position"insert(5, x) بۆ «شوێنی پێنجەم» | x becomes the 6th elementx دەبێتە شەشەمین | insert(4, x) |
a.index(x) without checkinga.index(x) بەبێ پشکنین | ValueError if x is missingئەگەر x نەبێت ValueError | if x in a: first |
| Dividing by a fixed 10 after appendingدابەشکردن بە 10ی جێگیر دوای append | Wrong averageتێکڕای هەڵە | / len(numbers) |
append()mistake_append_none.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange']
fruits = fruits.append('kiwi')
print(fruits)
fruits.append('fig')None
Traceback (most recent call last):
File "mistake_append_none.py", line 4, in <module>
fruits.append('fig')
^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'append'Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
append()returnsNone, and thatNonereplaces the list.append()Noneدەگەڕێنێتەوە و ئەوNoneـە جێگەی دەگرێتەوە.
append() یەک نرخ وەردەگرێتmistake_append_two.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange']
fruits.append('kiwi', 'fig')Traceback (most recent call last):
File "mistake_append_two.py", line 2, in <module>
fruits.append('kiwi', 'fig')
TypeError: list.append() takes exactly one argument (2 given)add()ـی نییەmistake_add.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەfruits = ['apple', 'orange']
fruits.add('kiwi')Traceback (most recent call last):
File "mistake_add.py", line 2, in <module>
fruits.add('kiwi')
^^^^^^^^^^
AttributeError: 'list' object has no attribute 'add'Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
add()belongs to sets (and Java'sArrayList); a Python list usesappend().add()هی (وArrayListـی Java)؛ لەappend()بەکار دەهێنێت.
Exercisesڕاهێنانەکان
Ask for items until the user types done. Store them in a list and then print how many items there are and the list itself.
داوای بڕگە بکە تا done دەنووسێت. لە هەڵیانبگرە و پاشان چاپ بکە چەند بڕگە هەیە و خودی .
Hintئاماژە
Check for done before you append.
پێش append بپشکنە بزانە doneـە یان نا.
Show answerوەڵامەکە پیشان بدە
shopping = []
while True:
item = input("Item (or done): ")
if item == "done":
break
shopping.append(item)
print("You need", len(shopping), "items:", shopping)Item (or done): bread Item (or done): tea Item (or done): sugar Item (or done): done You need 3 items: ['bread', 'tea', 'sugar']
while True with break is the sentinel pattern from The while loop; done itself is never appended.
while True لەگەڵ break شێوازی لە خولی while؛ خودی done هەرگیز append ناکرێت.
waiting = ["Karwan", "Hana", "Soran"]. Dilan has an appointment and goes to the front; Lana arrives late and goes to the end. Print the list after each change, then the index of Soran.
waiting = ["Karwan", "Hana", "Soran"]. Dilan کاتی دیاریکراوی هەیە و دەچێتە پێشەوە؛ Lana درەنگ دێت و دەچێتە کۆتایی. دوای هەر گۆڕانکارییەک چاپ بکە، پاشان Soran.
Show answerوەڵامەکە پیشان بدە
waiting = ["Karwan", "Hana", "Soran"]
waiting.insert(0, "Dilan")
print(waiting)
waiting.append("Lana")
print(waiting)
print(waiting.index("Soran"))['Dilan', 'Karwan', 'Hana', 'Soran'] ['Dilan', 'Karwan', 'Hana', 'Soran', 'Lana'] 3
insert(0, …) puts Dilan first and pushes everyone else one place on, so Soran moves from index 2 to index 3.
insert(0, …) Dilan دەکاتە یەکەم و هەموو ئەوانی تر یەک شوێن پاڵ دەنێت، بۆیە Soran لە 2ەوە دەچێتە 3.
Without running it, write down the list printed by this program, its length and the index of 15.
بەبێ جێبەجێکردن، ئەو بنووسە کە ئەم چاپی دەکات، درێژییەکەی و 15.
nums = [5, 10]
nums.append(20)
nums.insert(0, 1)
nums.insert(-1, 15)
nums.extend([25, 30])
print(nums)
print(len(nums), nums.index(15))Show answerوەڵامەکە پیشان بدە
nums = [5, 10]
nums.append(20)
nums.insert(0, 1)
nums.insert(-1, 15)
nums.extend([25, 30])
print(nums)
print(len(nums), nums.index(15))[1, 5, 10, 15, 20, 25, 30] 7 3
Step by step: [5, 10] → [5, 10, 20] → [1, 5, 10, 20] → insert(-1, 15) goes before the last element: [1, 5, 10, 15, 20] → [1, 5, 10, 15, 20, 25, 30].
هەنگاو بە هەنگاو: [5, 10] ← [5, 10, 20] ← [1, 5, 10, 20] ← insert(-1, 15) دەچێتە پێش دوایین : [1, 5, 10, 15, 20] ← [1, 5, 10, 15, 20, 25, 30].
votes = ["Dilan", "Aram", "Dilan", "Hana", "Dilan", "Aram"]. Print how many votes Dilan and Aram got, and the number (counting from 1) of the first vote for Hana.
votes = ["Dilan", "Aram", "Dilan", "Hana", "Dilan", "Aram"]. چاپ بکە Dilan و Aram چەند دەنگیان هێناوە و ژمارەی (لە 1ەوە) یەکەم دەنگ بۆ Hana.
Show answerوەڵامەکە پیشان بدە
votes = ["Dilan", "Aram", "Dilan", "Hana", "Dilan", "Aram"]
print("Dilan:", votes.count("Dilan"))
print("Aram:", votes.count("Aram"))
print("First vote for Hana is vote number", votes.index("Hana") + 1)Dilan: 3 Aram: 2 First vote for Hana is vote number 4
index() gives 3, a position counted from 0; people count from 1, so add 1.
index() 3 دەدات، شوێنێک کە لە 0ەوە دەژمێردرێت؛ خەڵک لە 1ەوە دەژمێرن، بۆیە 1ی بخە سەر.
index() finds only the first match. Using the same votes list, build a list of all the indexes where "Dilan" appears.
index() تەنها یەکەم هاوتا دەدۆزێتەوە. بە هەمان votes، لە هەموو ئەو شوێنانە () دروست بکە کە "Dilan"ی تێدا هاتووە.
Hintئاماژە
Start with positions = [] and loop with enumerate(votes).
بە positions = [] دەست پێ بکە و بە enumerate(votes) بسووڕێوە.
Show answerوەڵامەکە پیشان بدە
votes = ["Dilan", "Aram", "Dilan", "Hana", "Dilan", "Aram"]
positions = []
for i, name in enumerate(votes):
if name == "Dilan":
positions.append(i)
print(positions)[0, 2, 4]
enumerate() gives each index with its name; every match is appended to positions.
enumerate() هەر لەگەڵ ناوەکەی دەدات؛ هەر هاوتایەک بۆ positions append دەکرێت.
numbers = [12, -7, 0, 5, -3, 8, -1]. Build two new lists from it, positives and negatives, and print both. Zero is neither positive nor negative, so it goes into neither list.
numbers = [12, -7, 0, 5, -3, 8, -1]. دوو نوێی لێ دروست بکە، positives و negatives و هەردووکیان چاپ بکە. سفر نە موجەبە و نە سالب، بۆیە ناچێتە هیچ کامیانەوە.
Hintئاماژە
Start with two empty lists. Inside one loop, test n > 0 and n < 0 with if and elif.
بە دوو بەتاڵ دەست پێ بکە. لە ناو یەک بە if و elif n > 0 و n < 0 تاقی بکەرەوە.
Show answerوەڵامەکە پیشان بدە
numbers = [12, -7, 0, 5, -3, 8, -1]
positives = []
negatives = []
for n in numbers:
if n > 0:
positives.append(n)
elif n < 0:
negatives.append(n)
print("positive:", positives)
print("negative:", negatives)
print("original:", numbers)positive: [12, 5, 8] negative: [-7, -3, -1] original: [12, -7, 0, 5, -3, 8, -1]
One loop fills two lists, each with append(), and the elements keep their order. Zero fails both tests, so it is skipped; the original list does not change. If your task counts 0 as positive, write n >= 0.
یەک دوو پڕ دەکاتەوە، هەریەکەیان بە append() و ڕیزەکەی خۆیان دەپارێزن. سفر لە هەردوو تاقیکردنەوەکە دەرناچێت، بۆیە پشتگوێ دەخرێت؛ ڕەسەن ناگۆڕێت. ئەگەر ئەرکەکەت سفر بە موجەب دادەنێت، بنووسە n >= 0.
Summaryپوختە
append(x)adds one element at the end; it changes the list and returnsNone.insert(i, x)puts x at index i and moves the later elements one place right. Any index works: past the end appends, negative counts from the end.extend(seq)(or+=) adds every item of a sequence;append(seq)adds the sequence as ONE element.- Fill a list from input with
append(int(input(...))), never witheval(). x in aandx not in aanswer True or False by a linear search, element by element: 1 comparison in the best case, in the worst case.a.index(x)gives the first position of x and raisesValueErrorif x is missing;a.count(x)counts matches.- After adding elements, compute averages with
len(), not a fixed count.
append(x)یەک دەخاتە کۆتایی؛ دەگۆڕێت وNoneدەگەڕێنێتەوە.insert(i, x)x لە iدا دادەنێت و دواتر یەک شوێن بەرەو ڕاست دەجووڵێنێت. هەر کار دەکات: لە دوای کۆتاییەوە append دەکات و سالب لە کۆتاییەوە دەژمێرێت.extend(seq)(یان+=) هەموو بڕگەیەکی زیاد دەکات؛append(seq)وەک یەک زیاد دەکات.- لە بە
append(int(input(...)))پڕ بکەرەوە، هەرگیز بەeval(). x in aوx not in aبە ، بە ، وەڵامی True یان False دەدەنەوە: لە یەک بەراورد و لە بەراورد.a.index(x)یەکەم شوێنی x دەدات و ئەگەر x نەبێتValueErrorدروست دەکات؛a.count(x)هاوتاکان دەژمێرێت.- دوای زیادکردنی ، تێکڕا بە
len()حیساب بکە، نەک بە ژمارەیەکی جێگیر.
a = [3, 4]. What do a.append([5]) and, separately, a.extend([5]) give?a = [3, 4]. a.append([5]) و بە جیا a.extend([5]) چی دەدەن؟
[3, 4, [5]] and [3, 4, 5].
[3, 4, [5]] و [3, 4, 5].
Where does insert(0, x) put x, and where does insert(-1, x) put it?insert(0, x) x لە کوێ دادەنێت و insert(-1, x) لە کوێ؟
At the front; and just before the last element.
لە پێشەوە. دووەمیان ڕێک پێش دوایین .
How do you avoid the ValueError of index()?چۆن خۆت لە ValueErrorـی index() دەپارێزیت؟
Check if x in a: first, or use a.count(x), which returns 0 for a missing value.
سەرەتا if x in a: بپشکنە، یان a.count(x) بەکار بهێنە کە بۆ کە نییە 0 دەگەڕێنێتەوە.
Why does Lab 4 use a while loop instead of for?بۆچی تاقیگەی 4 خولی while بەکار دەهێنێت لەبری for؟
The number of inputs is not known in advance; the loop stops when len(mylist) reaches 10.
ژمارەی پێشتر نازانرێت؛ کاتێک len(mylist) دەگاتە 10 دەوەستێت.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
Negative indexes count from the end of a list; tuples are lists you cannot change; sets keep different values, unordered, with fast membership tests.
لە کۆتایی دەژمێرن؛ وەک ، بەڵام ناگۆڕدرێن؛ جیاواز بەبێ ڕیزبەندی هەڵدەگرن و بە خێرایی دەزانیت تێیاندایە یان نا.
Watch 5:18–8:53: append(), insert() and extend(), and the difference between inserting a list and extending with it. Stops before remove().
لە 5:18 تا 8:53 سەیر بکە: append()، insert() و extend()، هەروەها جیاوازیی نێوان خستنەناوەوەی و درێژکردنەوە پێی. پێش remove() ڕادەوەستێت.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Removing Items, Joining and Comparing Listsلابردنی دانەکان، پێکەوەلکاندن و بەراوردکردنی لیستەکان
Related lecturesوانە پەیوەندیدارەکان
- Removing Items, Joining and Comparing Listsلابردنی دانەکان، پێکەوەلکاندن و بەراوردکردنی لیستەکان
- sum, max, min and Sortingsum، max، min و ڕیزکردن
- Input and Outputنێوخستە و دەرخستە
- Controlling Loops: break and continueکۆنترۆڵکردنی خولەکان:
breakوcontinue - The Python You Need for the AI Labsئەو Pythonـەی بۆ تاقیگەکانی ژیریی دەستکرد پێویستە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- The Python Tutorial, 5.1 More on Lists (append, extend, insert, index, count)
- Python Standard Library: Built-in Types — common and mutable sequence operations
- Python Language Reference: Membership test operations
- Python Design and History FAQ: How are lists implemented in CPython?
- Python Standard Library: Built-in Functions (input, int, eval warning)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.