PythonPython · Chapterبەش 9 · Lectureوانە 9.1
Lists: Creating and Indexingلیستەکان: دروستکردن و ئیندێکسەکان
What a Python list is and why programs need one; creating lists with [] and list(); reading and changing elements by index; negative indexes and the valid range; slices; three ways to loop over a list; and how lists differ from strings and from fixed-size arrays.
لە چییە و بۆچی پێویستیان پێیەتی؛ دروستکردنی بە [] و list()؛ خوێندنەوە و گۆڕینی بە ؛ و کام دروستن؛ ؛ سێ ڕێگەی سووڕانەوە بەسەر ؛ جیاوازیی لەگەڵ و قەبارە جێگیر.
What you will learnچی فێر دەبیت
- Explain what a list is and create lists with square brackets and with
list(). - Read and change elements with positive and negative indexes, and know which indexes are valid.
- Explain how a list differs from a string and from a fixed-size array.
- Take slices of a list and loop over it by element, by index and with
enumerate().
- ڕوونی بکەیتەوە چییە و بە کەوانەی چوارگۆشە و بە
list()دروست بکەیت. - بە موجەب و سالب بخوێنیتەوە و بگۆڕیت و بزانیت کام دروستن.
- ڕوونی بکەیتەوە چۆن لە و لە قەبارە جێگیر جیاوازە.
- وەربگریت و بەسەریدا بسووڕێیتەوە بە ، بە و بە
enumerate().
One name for many valuesیەک ناو بۆ چەندین نرخ
Imagine a teacher who stores marks in a program. With three students you could write mark1, mark2 and mark3. With forty students you would need forty variables, and no loop could walk through them, because each one has a different name.
وای دابنێ مامۆستایەک نمرەکان لە هەڵدەگرێت. بۆ سێ خوێندکار دەتوانیت mark1، mark2 و mark3 بنووسیت. بۆ چل خوێندکار چل پێویست دەبێت و هیچ ناتوانێت بەسەریاندا بڕوات، چونکە هەریەکەیان ناوێکی جیاوازی هەیە.
mark1 = 78
mark2 = 91
mark3 = 65
print(mark1, mark2, mark3)
marks = [78, 91, 65]
print(marks)
print(len(marks))78 91 65 [78, 91, 65] 3
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-4
Three separate names: fine for three values, hopeless for forty.
سێ ناوی جیا: بۆ سێ باشە، بۆ چل بێکەڵکە.
- Lineدێڕی 6
One name,
marks, holds all three values in order.یەک ناو،
marks، هەر سێ بە ڕیز هەڵدەگرێت.- Lineدێڕی 8
len()tells how many values the list holds.len()دەڵێت چەند هەڵدەگرێت.
A list solves this. It keeps a collection of values of any size, in order, under one name. Each value in it is an element, and each element has a position number, its index. Because the positions are numbers, a loop can visit every element, whether there are three or three thousand.
ئەم کێشەیە چارەسەر دەکات. کۆمەڵێک بە هەر قەبارەیەک بێت، بە ڕیز، لە ژێر یەک ناودا هەڵدەگرێت. هەر تێیدا و هەر ژمارەی شوێنی خۆی هەیە، کە . لەبەر ئەوەی شوێنەکان ژمارەن، دەتوانێت سەردانی هەموو بکات، جا سێ دانە بن یان سێ هەزار.
An ordered, changeable collection of values, written in square brackets: [3, 8, 0]. Items are numbered from 0, and a list can grow or shrink. Python calls it a list; Dart has List; PHP uses an for the same job.
کۆکراوەیەکی ڕیزکراو و گۆڕاوی نرخەکانە کە لەناو کەوانەی چوارگۆشەدا دەنووسرێت: [3, 8, 0]. دانەکان لە 0ەوە ژمارە دەکرێن و لیست دەتوانێت گەورە یان بچووک ببێتەوە. Python پێی دەڵێت list و Dart List؛ PHP بۆ هەمان کار بەکار دەهێنێت.
One name for many valuesیەک ناو بۆ چەندین نرخ
A train with numbered carriagesشەمەندەفەرێک بە فارگۆنی ژمارەدار
Picture a train. The engine carries the train's name: that is the list's name, cities. Behind it come carriages, numbered 0, 1, 2, 3 from the engine. Each carriage carries some cargo: that is the element. To find the cargo you want, you ask for a carriage number: cities[2] means "carriage 2". A new carriage can be coupled at the end of the train, and the train gets longer.
شەمەندەفەرێک بهێنە بەرچاو. ناوی شەمەندەفەرەکە لەسەر سەرەکەی نووسراوە: ئەوە ناوی ، cities. لە دوایەوە فارگۆنەکان دێن کە لە سەرەکەوە بە 0، 1، 2، 3 ژمارە کراون. هەر فارگۆنێک بارێک هەڵدەگرێت: ئەوە . بۆ دۆزینەوەی ئەو بارەی دەتەوێت، داوای ژمارەی فارگۆنەکە دەکەیت: cities[2] واتە «فارگۆنی 2». دەکرێت فارگۆنێکی نوێ بە کۆتایی شەمەندەفەرەکەوە ببەسترێت و شەمەندەفەرەکە درێژتر دەبێت.
Where the analogy stops workingسنووری ئەم نموونەیە
The analogy breaks in three places. A real carriage keeps its painted number, but in a list the index is only the position: when an element is put in or taken out in the middle, every element after it gets a new index. A real train always has carriages, while a list can be empty, []. And a list can hold very different things side by side, a number next to a text, which no railway would allow.
ئەم بەراوردە لە سێ شوێندا ڕاست نییە. فارگۆنی ڕاستەقینە ژمارە بۆیەکراوەکەی دەمێنێتەوە، بەڵام لە تەنها شوێنەکەیە: کاتێک لە ناوەڕاستدا زیاد دەکرێت یان لادەبرێت، هەموو دوای ئەو نوێ وەردەگرن. شەمەندەفەری ڕاستەقینە هەمیشە فارگۆنی هەیە، بەڵام دەکرێت بەتاڵ بێت، []. هەروەها دەتوانێت شتی زۆر جیاواز لە تەنیشت یەکەوە هەڵبگرێت، ژمارەیەک لە تەنیشت دەقێکەوە، کە هیچ هێڵێکی ئاسن ڕێگەی پێ نادات.
Creating a listدروستکردنی لیستێک
Write the elements between square brackets [ ] and separate them with commas. Empty brackets [] make an empty list, a list with no elements yet. The elements can all be of the same type, or of mixed types: [2, "three", 4] is a perfectly good list. The list keeps its elements in the order you wrote them.
لە نێوان کەوانەی چوارگۆشە [ ] بنووسە و بە کۆما لێکیان جیا بکەرەوە. کەوانەی بەتاڵ [] بەتاڵ دروست دەکات، کە هێشتا هیچ تێدا نییە. دەکرێت هەموویان لە یەک جۆر بن، یان جۆراوجۆر بن: [2, "three", 4] تەواو دروستە. خۆی بەو ڕیزەیە هەڵدەگرێت کە نووسیوتن.
list1 = [] # an empty list
list2 = [2, 3, 4] # three integers
list3 = ["red", "green"] # two strings
list4 = [2, "three", 4] # mixed types are allowed
print(list1, list2, list3, list4)
print(len(list1), len(list2), len(list3), len(list4))[] [2, 3, 4] ['red', 'green'] [2, 'three', 4] 0 3 2 3
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
An empty list: nothing between the brackets.
بەتاڵ: هیچ لە نێوان کەوانەکاندا نییە.
- Lineدێڕی 4
Mixed types in one list are allowed.
جۆری جیاواز لە یەک ڕێگەپێدراوە.
- Lineدێڕی 6
len()counts the elements; the empty list has 0.len()دەژمێرێت؛ بەتاڵ 0 هەیە.
When Python prints a list, it shows the brackets and commas too, and it shows strings in single quotes, even if you typed double quotes (unless the text itself contains a single quote). len() is a built-in function that works on every sequence: for a list it gives the number of elements.
کاتێک چاپ دەکات، کەوانە و کۆماکانیش پیشان دەدات و لە ناو تاکدا (') پیشان دەدات، تەنانەت ئەگەر جووتت (") نووسیبێت (مەگەر دەقەکە خۆی تاکی تێدا بێت). len() کە لەسەر هەموو کار دەکات: بۆ ژمارەی دەدات.
Creating a listدروستکردنی لیستێک
The list class and list()کلاسی list و list()
Every list belongs to the list class. A class describes a kind of object: what it stores and which methods (actions) it offers. The list class gives every list methods for adding, finding and removing elements, which the next lessons teach. You can also make a list by calling list(), the class's constructor. Given nothing, it makes an empty list; given another sequence, such as a range or a string, it makes a list of its items.
هەموو سەر بە listـە. جۆرێک وەسف دەکات: چی هەڵدەگرێت و چ کارێک دەکات، کە پێیان دەوترێت . list بە هەموو دەدات بۆ زیادکردن، دۆزینەوە و لابردنی ، کە وانەکانی داهاتوو فێری دەکەن. دەتوانیت بە بانگکردنی list()یش دروست بکەیت، کە . ئەگەر هیچی پێ نەدەیت بەتاڵ دروست دەکات؛ ئەگەر تری پێ بدەیت، وەک range یان ، لە بڕگەکانی دروست دەکات.
list()list_constructor.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەlist1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"]) # Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c, d
print(list1, list2, list3, list4, list5)
print(type(list2))[] [2, 3, 4] ['red', 'green', 'blue'] [3, 4, 5] ['a', 'b', 'c', 'd'] <class 'list'>
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
range(3, 6)gives 3, 4, 5;list()collects them.range(3, 6)ژمارەکانی 3، 4 و 5 دەدات؛list()کۆیان دەکاتەوە.- Lineدێڕی 5
A string becomes a list of its characters.
دەبێتە لە خۆی.
- Lineدێڕی 7
type()confirms the class:list.type()پشتڕاست دەکاتەوە:list.
A list grows and shrinksلیست گەورە و بچووک دەبێت
In many other programming languages, such as Java and C, a row of values is stored in an array. An array has a fixed size: you say how many places it has when you create it, and that never changes. A Python list is flexible: it can grow and shrink while the program runs. A common pattern is to start with an empty list and add elements one by one with append().
لە زۆر تردا، وەک Java و C، ڕیزێک لە هەڵدەگیرێت. قەبارەیەکی جێگیری هەیە: کاتی دروستکردنی دەڵێیت چەند شوێنی هەیە و ئەوە هەرگیز ناگۆڕێت. لە نەرمە: لە کاتی کارکردنی گەورە و بچووک دەبێت. شێوازێکی باو ئەوەیە بە بەتاڵ دەست پێ بکەیت و بە append() یەک یەک زیاد بکەیت.
country = []
country.append("Kurdistan")
country.append("Egypt")
for j in country:
print(j)Kurdistan Egypt
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Start with an empty list.
بە بەتاڵ دەست پێ بکە.
- Lineدێڕی 2-3
Each
append()adds one element at the end: the list grows from 0 to 2 elements.هەر
append()ێک دەخاتە کۆتایی: لە 0ەوە دەبێتە 2 .- Lineدێڕی 4-5
A
forloop visits the elements in order.بە ڕیز سەردانی دەکات.
You will learn append() properly in Adding to a list and finding items. How Java's typed, fixed-size arrays differ from Python's lists is introduced in Programming languages.
append() بە تەواوی لە زیادکردن بۆ لیستێک و دۆزینەوەی دانەکان فێر دەبیت. جیاوازیی Java، کە جۆریان دیاریکراوە و قەبارەیان جێگیرە، لەگەڵ لە زمانەکانی بەرنامەسازی ناسێنراوە.
Reaching an element by its indexگەیشتن بە دانەیەک بە ئیندێکسەکەی
Each element is reached with an integer index i, written in square brackets after the list's name: values[i]. These brackets are called the subscript operator. They work exactly as with the characters of a string (see Working with strings): counting starts at 0, so the first element is values[0] and the last one is values[len(values) - 1].
هەر بە دەگاتێ، کە وەک i و لە دوای ناوی لە ناو کەوانەی چوارگۆشەدا دەنووسرێت: values[i]. بەم کەوانانە دەوترێت (subscript operator). ڕێک وەک کار دەکەن (بڕوانە کارکردن لەگەڵ زنجیرەنووسەکان): ژماردن لە 0ەوە دەست پێ دەکات، بۆیە یەکەم values[0]ـە و دوایینیان values[len(values) - 1]ـە.
values = [32, 54, 67, 29, 35, 80, 115]
print(values[0])
print(values[5]) # Prints the element at index 5
print(values[6])
print(len(values))32 80 115 7
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Index 5 is the sixth element: 80.
5 شەشەمین : 80.
- Lineدێڕی 4
With 7 elements the last index is 6.
بە 7 ، دوایین 6ە.
In Kurdish: how to make a Python list, read items by index (also the negative index -1), change an item and join two lists.
بە کوردی: چۆن دروست دەکەیت، بە دەخوێنیتەوە (لەوانە نەرێنیی -1)، دەگۆڕیت و دوو پێکەوە دەلکێنیت.
Kurdish video, whole (7:52): making a list, index 0 and -1, changing an item, joining lists with +.
ڤیدیۆیەکی کوردی، هەموو ڤیدیۆکە (7:52): دروستکردنی ، 0 و -1، گۆڕینی و بە +.
Reaching an element by its indexگەیشتن بە دانەیەک بە ئیندێکسەکەی
Changing an elementگۆڕینی دانەیەک
A list is mutable: you can replace any element. Put the indexed element on the left of =, as if it were a variable: values[5] = 80 throws away the old value at index 5 and stores 80 there. The other elements do not move.
: دەتوانیت هەر بگۆڕیت. لەگەڵ بخە لای چەپی =، وەک ئەوەی بێت: values[5] = 80 کۆنی 5 فڕێ دەدات و 80 لەوێ هەڵدەگرێت. تر ناجووڵێن.
values = [32, 54, 67, 29, 35, 60, 115]
values[5] = 80
print(values)
values[0] = values[0] + 1
print(values)[32, 54, 67, 29, 35, 80, 115] [33, 54, 67, 29, 35, 80, 115]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
60 at index 5 is replaced by 80.
60 لە 5دا بە 80 دەگۆڕدرێت.
- Lineدێڕی 4
Read the old value, add 1, store the result in the same place.
کۆن بخوێنەوە، 1ی بخە سەر و ئەنجامەکە لە هەمان شوێندا هەڵبگرە.
Reaching an element by its indexگەیشتن بە دانەیەک بە ئیندێکسەکەی
Lists and strings: alike and differentلیستەکان و زنجیرەنووسەکان: لێکچوون و جیاوازی
Lists and strings are both sequences: their items stand in a fixed order and [] reaches any of them. But they differ in two ways. First, a list can hold values of any type, while a string holds only characters. Second, strings are immutable: their characters cannot be replaced. Lists are mutable.
و هەردووکیان : بڕگەکانیان بە ڕیزێکی جێگیر وەستاون و [] دەگاتە هەریەکێکیان. بەڵام لە دوو ڕووەوە جیاوازن. یەکەم، دەتوانێت لە هەر جۆرێک هەڵبگرێت، بەڵام تەنها هەڵدەگرێت. دووەم، : ناگۆڕدرێنەوە. .
s = "Python"
print(s[0])
s[0] = "J"P
Traceback (most recent call last):
File "string_immutable.py", line 3, in <module>
s[0] = "J"
~^^^
TypeError: 'str' object does not support item assignmentExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Reading a character works, as with a list.
خوێندنەوەی کار دەکات، وەک لە .
- Lineدێڕی 3
Changing one does not: strings are immutable.
گۆڕینی کار ناکات: .
Reaching an element by its indexگەیشتن بە دانەیەک بە ئیندێکسەکەی
Which indexes are allowed?کام ئیندێکسەکان ڕێگەپێدراون؟
The lecture sums up this screen in one labelled example: the name of the list variable, an empty list, a list with initial values, and brackets to write and read one element. Here it is with i = 2.
وانەکە ئەم بابەتە بە یەک نموونەی تێبینیدار کورت دەکاتەوە: ناوی ، بەتاڵ، بە سەرەتاییەوە و کەوانە بۆ نووسین و خوێندنەوەی یەک . لێرەدا بە i = 2.
more_values = [] # Creates an empty list
values = [32, 54, 67, 29, 35, 80, 115] # Creates a list with initial values
i = 2
values[i] = 0 # Use brackets to access an element
element = values[i]
print(values, element, more_values)[32, 54, 0, 29, 35, 80, 115] 0 []
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Name of the list variable, and an empty list. (The slide wrote
moreValues; PEP 8 prefersmore_values.)ناوی و بەتاڵ. (سلایدەکە
moreValuesی نووسیبوو؛ PEP 8more_valuesی پێ باشترە.)- Lineدێڕی 2
A list created with initial values.
کە بە سەرەتاییەوە دروست کراوە.
- Lineدێڕی 4
Brackets on the left of
=: write into the element at indexi.کەوانە لە لای چەپی
=: نووسین لە ناوi.- Lineدێڕی 5
Brackets on the right: read the element.
کەوانە لە لای ڕاست: خوێندنەوەی .
An index must be at least 0 and less than the number of elements. With 7 elements, the indexes 0 to 6 exist; 7 does not. Asking for a missing index is an out-of-range error: Python raises an IndexError exception, and if nothing handles it the program stops at that line.
دەبێت لانیکەم 0 بێت و لە ژمارەی کەمتر بێت. بە 7 ، 0 تا 6 هەن؛ 7 نییە. داواکردنی کە بوونی نییە دەرچوون لە سنوورە (out of range): IndexError دروست دەکات و ئەگەر هیچ شتێک چارەسەری نەکات لەو دێڕەدا دەوەستێت.
values = [32, 54, 67, 29, 35, 80, 115]
print(len(values))
print(values[7])7
Traceback (most recent call last):
File "index_error.py", line 3, in <module>
print(values[7])
~~~~~~^^^
IndexError: list index out of rangeExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
The valid indexes are 0 to 6, so the program stops here.
تەنها 0 تا 6 دروستن، بۆیە لێرەدا دەوەستێت.
Negative indexes: counting from the endئیندێکسە سالبەکان: ژماردن لە کۆتاییەوە
Python, unlike many other languages, also lets you use negative subscripts. They reach the elements in reverse order: values[-1] is the last element, values[-2] the second-to-last, and so on. This is the easiest way to get the last element without writing len().
، بە پێچەوانەی زۆر زمانی ترەوە، ڕێگەت دەدات بەکار بهێنیت. ئەمانە بە ڕیزی پێچەوانە دەگەنە : values[-1] دوایین ، values[-2] ئەوەی پێش دوایین و بەم شێوەیە. ئەمە ئاسانترین ڕێگەیە بۆ وەرگرتنی دوایین بەبێ نووسینی len().
value = [12, 45, 2, 56, 8, 34, 1, 34, 9, 0, 45]
last = value[-1]
print("The last element in the list is", last)The last element in the list is 45
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
-1always means the last element, whatever the length.-1هەمیشە واتە دوایین ، درێژییەکە هەرچەندێک بێت.
How does Python find a negative index? It adds the length of the list: values[-k] means values[len(values) - k]. The animation walks through it with a 10-element list.
چۆن دەدۆزێتەوە؟ درێژیی زیاد دەکات: values[-k] واتە values[len(values) - k]. ئەنیمەیشنەکە بە 10 دانەیی نیشانی دەدات.
![Animation with values = [32, 54, 67, 29, 35, 60, 115, 44, 100, 65]. Every box shows its index 0 to 9 above and its negative index -10 to -1 below. A pointer starts at the right end: values[-1] becomes values[10 - 1], which is values[9], 65; then values[-2] is values[8], 100; values[-3] is values[7], 44. Then the pointer jumps to values[-10], which is values[0], 32, the first element only because the list has 10 elements. The last frame shows values[-11] → IndexError: here the index must be between -10 and 9.](/_astro/py-lists-negative-walk.en.1mVqBUMH.gif)
![Animation with values = [32, 54, 67, 29, 35, 60, 115, 44, 100, 65]. Every box shows its index 0 to 9 above and its negative index -10 to -1 below. A pointer starts at the right end: values[-1] becomes values[10 - 1], which is values[9], 65; then values[-2] is values[8], 100; values[-3] is values[7], 44. Then the pointer jumps to values[-10], which is values[0], 32, the first element only because the list has 10 elements. The last frame shows values[-11] → IndexError: here the index must be between -10 and 9.](/_astro/py-lists-negative-walk.ckb.Dw5hgSI4.gif)
| Element | Index | Negative index |
|---|---|---|
| 32 | values[0] | values[-10] |
| 54 | values[1] | values[-9] |
| 67 | values[2] | values[-8] |
| 29 | values[3] | values[-7] |
| 35 | values[4] | values[-6] |
| 60 | values[5] | values[-5] |
| 115 | values[6] | values[-4] |
| 44 | values[7] | values[-3] |
| 100 | values[8] | values[-2] |
| 65 | values[9] | values[-1] |
Negative indexes: counting from the endئیندێکسە سالبەکان: ژماردن لە کۆتاییەوە
Is values[-10] always the first element?ئایا values[-10] هەمیشە یەکەم دانەیە؟
The slide's code used an 11-element list called value, but its table showed a different, 10-element list called values, and it said "values[-10] is the first element". That is true only for the 10-element list. In general the first element is values[-len(values)]. Run both lists side by side:
کۆدی سلایدەکە 11 دانەیی بە ناوی value بەکار هێنابوو، بەڵام خشتەکەی جیاوازی 10 دانەیی بە ناوی values پیشان دەدا و دەیگوت «values[-10] یەکەم ». ئەمە تەنها بۆ 10 دانەیی ڕاستە. بە گشتی یەکەم values[-len(values)]ـە. هەردوو لە تەنیشت یەکەوە جێبەجێ بکە:
-10 depends on the length-10 بەستراوە بە درێژییەوەnegative_check.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەvalues = [32, 54, 67, 29, 35, 60, 115, 44, 100, 65] # 10 elements
print(values[-1], values[-2], values[-10])
value = [12, 45, 2, 56, 8, 34, 1, 34, 9, 0, 45] # 11 elements
print(len(value))
print(value[-2], value[-10], value[-11])
print(value[-len(value)])65 100 32 11 0 45 12 12
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
10 elements:
-10is the first element, 32.10 :
-10یەکەم ، 32.- Lineدێڕی 6
11 elements:
-10is the second element, 45; the first is-11.11 :
-10دووەم ، 45؛ یەکەمیان-11ـە.- Lineدێڕی 7
-len(value)is always the first element.-len(value)هەمیشە یەکەم .
Negative indexes: counting from the endئیندێکسە سالبەکان: ژماردن لە کۆتاییەوە
The full range of valid indexesئیندێکسەکان لە کوێوە تا کوێ دروستن؟
So for a list of length the valid indexes run from to . One step further, and Python raises IndexError, exactly as with a too-large positive index.
کەواتە بۆ بە درێژیی ، لە تا دروستن. یەک هەنگاو زیاتر و IndexError دروست دەکات، ڕێک وەک موجەبی زۆر گەورە.
-11 is outside a 10-element list-11 لە دەرەوەی لیستێکی 10 دانەییەnegative_error.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەvalues = [32, 54, 67, 29, 35, 60, 115, 44, 100, 65]
print(values[-10])
print(values[-11])32
Traceback (most recent call last):
File "negative_error.py", line 3, in <module>
print(values[-11])
~~~~~~^^^^^
IndexError: list index out of rangeSlices: several elements at onceلەتکردن: چەند دانەیەک بە یەکجار
Lists can be sliced exactly like strings (see Slicing): values[start:stop] takes the elements from index start up to, but not including, stop. Leave out start to begin at 0, leave out stop to go to the end, and add a step with a second colon. The result is a new list; the original is not changed.
ڕێک وەک دەکرێن (بڕوانە لەتکردن): values[start:stop] لە startەوە وەردەگرێت تا stop، بەڵام خودی stop تێدا نییە. ئەگەر start نەنووسیت لە 0ەوە دەست پێ دەکات، ئەگەر stop نەنووسیت تا کۆتایی دەڕوات و دەتوانیت بە دوو خاڵی دووەم هەنگاوێک زیاد بکەیت. ئەنجامەکە نوێیە؛ ڕەسەن ناگۆڕێت.
values = [32, 54, 67, 29, 35, 60, 115, 44, 100, 65]
print(values[2:5])
print(values[:3])
print(values[-3:])
print(values[::2])
print(values[::-1])
print(values[8:50])
print(values)[67, 29, 35] [32, 54, 67] [44, 100, 65] [32, 67, 35, 115, 100] [65, 100, 44, 115, 60, 35, 29, 67, 54, 32] [100, 65] [32, 54, 67, 29, 35, 60, 115, 44, 100, 65]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Indexes 2, 3 and 4; index 5 is the stop and is left out.
2، 3 و 4؛ 5 کۆتاییە و دەرەوە دەمێنێت.
- Lineدێڕی 4
The last three elements.
دوایین سێ .
- Lineدێڕی 5-6
A step of 2 takes every second element; a step of
-1walks backwards.هەنگاوی 2 هەموو دووەم وەردەگرێت؛ هەنگاوی
-1بە پێچەوانەوە دەڕوات.- Lineدێڕی 7
Slices never raise
IndexError: a stop past the end is cut to the end.هەرگیز
IndexErrorنادات: کۆتاییەک کە لە دوای بێت تا کۆتایی کورت دەکرێتەوە.- Lineدێڕی 8
The original list is unchanged.
ڕەسەن نەگۆڕاوە.
How a slice values[start:stop] takes elements up to, but not including, stop, and how a step skips elements.
بە values[start:stop] چۆن وەردەگرێت تا stop، بەڵام stop خۆی ناگرێتەوە، هەروەها هەنگاو چۆن بەسەر باز دەدات.
Watch from 2:14: slicing, then the step (5:36). The first two minutes repeat indexing and negative indexes.
لە 2:14 بەدواوە سەیر بکە: ، پاشان هەنگاو (5:36). دوو خولەکی یەکەم دووبارەکردنەوەی و .
Three ways to loop over a listسێ ڕێگە بۆ سووڕانەوە بەسەر لیستێکدا
A for loop can walk over a list in three ways: over the elements, over the indexes, or over both. The lecture asks what three short loops over the same list print. Try each one before you open the answer.
دەتوانێت بە سێ ڕێگە بەسەر بڕوات: بەسەر ، بەسەر یان بەسەر هەردووکیان. وانەکە دەپرسێت سێ کورت بەسەر هەمان چی چاپ دەکەن. پێش کردنەوەی وەڵامەکە هەریەکەیان تاقی بکەرەوە.
What does this loop print?
ئەم چی چاپ دەکات؟
a = [12, 5, 8, 4, 2, 0]
for i in a:
print(i)Show answerوەڵامەکە پیشان بدە
a = [12, 5, 8, 4, 2, 0]
for i in a:
print(i)12 5 8 4 2 0
The loop variable i takes each element in turn, so the six values are printed. (A name such as number would describe it better than i.)
i یەک لە دوای یەک هەر وەردەگرێت، بۆیە شەش چاپ دەکرێن. (ناوێکی وەک number باشتر لە i وەسفی دەکات.)
And this one?
ئەی ئەمەیان؟
a = [12, 5, 8, 4, 2, 0]
for i in range(len(a)):
print(i)Show answerوەڵامەکە پیشان بدە
a = [12, 5, 8, 4, 2, 0]
for i in range(len(a)):
print(i)0 1 2 3 4 5
range(len(a)) is range(6): the numbers 0 to 5. They are the indexes, not the elements, so 0 to 5 is printed.
range(len(a)) یەکسانە بە range(6): ژمارەکانی 0 تا 5. ئەمانە ، نەک ، بۆیە 0 تا 5 چاپ دەکرێت.
And this one?
ئەی ئەمەیان؟
a = [12, 5, 8, 4, 2, 0]
for i in range(len(a)):
print(i, a[i])Show answerوەڵامەکە پیشان بدە
a = [12, 5, 8, 4, 2, 0]
for i in range(len(a)):
print(i, a[i])0 12 1 5 2 8 3 4 4 2 5 0
The loop goes over the indexes, and a[i] uses each index to read the element: every line shows the index and its element.
بەسەر دەڕوات و a[i] هەر بەکار دەهێنێت بۆ خوێندنەوەی : هەر دێڕێک و پیشان دەدات.
| Loop | Gives youچی دەدات | Use it whenکەی بەکاری بهێنە |
|---|---|---|
for x in a: | each elementهەر | you only need the valuesتەنها پێویستە |
for i in range(len(a)): | each indexهەر | you must change elements, or compare neighboursدەبێت بگۆڕیت، یان دراوسێکان بەراورد بکەیت |
for i, x in enumerate(a): | index and element together و پێکەوە | you need both, for example to print positionsهەردووکیانت پێویستە، بۆ نموونە بۆ چاپکردنی شوێنەکان |
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 15:25–18:49, 'Looping Values': a for loop over a list and enumerate() for index and element.
لە 15:25 تا 18:49 سەیر بکە، بەشی Looping Values: بەسەر و enumerate() بۆ و .
Three ways to loop over a listسێ ڕێگە بۆ سووڕانەوە بەسەر لیستێکدا
enumerate(): index and element togetherenumerate(): ئیندێکس و دانە پێکەوە
Loop 3 is so common that Python has a built-in function for it: enumerate() gives pairs of (index, element). The loop line names both: for i, value in enumerate(a):. It reads more clearly than range(len(a)) and cannot get the index wrong. With start=1 the counting begins at 1, which is handy for numbered lists that people read.
3 ئەوەندە باوە کە بۆی هەیە: enumerate() جووتی (، ) دەدات. دێڕی ناوی هەردووکیان دەبات: for i, value in enumerate(a):. لە range(len(a)) ڕوونترە و ناتوانێت هەڵە بکات. بە start=1 ژماردن لە 1ەوە دەست پێ دەکات، کە بۆ ژمارەدار کە خەڵک دەیخوێنێتەوە بەسوودە.
enumerate()loop_enumerate.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەa = [12, 5, 8, 4, 2, 0]
for i, value in enumerate(a):
print(i, value)0 12 1 5 2 8 3 4 4 2 5 0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Each round gives one (index, element) pair;
iandvaluetake its two parts.هەر جووتێکی (، ) دەدات؛
iوvalueدوو بەشەکەی وەردەگرن.
cities = ["Erbil", "Sulaymaniyah", "Duhok", "Halabja"]
for number, city in enumerate(cities, start=1):
print(number, city)1 Erbil 2 Sulaymaniyah 3 Duhok 4 Halabja
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
start=1changes only the numbers printed; the real indexes still start at 0.start=1تەنها ئەو ژمارانە دەگۆڕێت کە چاپ دەکرێن؛ خۆیان هێشتا لە 0ەوە دەست پێ دەکەن.
Three ways to loop over a listسێ ڕێگە بۆ سووڕانەوە بەسەر لیستێکدا
Changing elements inside a loopگۆڕینی دانەکان لە ناو خولێکدا
To change the elements of a list in a loop you need their indexes. In for x in b: the loop variable x is only a name for the current value: giving x a new value does not touch the list.
بۆ گۆڕینی لە ناو پێویستە. لە for x in b:دا x تەنها ناوێکە بۆ ئێستا: دانانی نوێ بۆ x دەست لە نادات.
a = [12, 5, 8, 4, 2, 0]
for i in range(len(a)):
a[i] = a[i] * 2
print(a)
b = [12, 5, 8]
for x in b:
x = x * 2
print(b)[24, 10, 16, 8, 4, 0] [12, 5, 8]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
Through the index, each element is replaced: the list changes.
لە ڕێگەی هەر دەگۆڕدرێت: دەگۆڕێت.
- Lineدێڕی 7-8
xgets a new value, butbis untouched.xنوێ وەردەگرێت، بەڵامbدەستی لێ نادرێت.
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوودەدات | Fixچارەسەر |
|---|---|---|
Counting from 1: names[1] for the first nameژماردن لە 1ەوە: names[1] بۆ یەکەم ناو | You get the second element دووەم وەردەگریت | names[0] |
values[len(values)] | IndexError | values[len(values) - 1] or values[-1]values[len(values) - 1] یان values[-1] |
["Erbil" "Duhok"] | No error: the two strings join into one elementهیچ نییە: هەردوو دەبنە یەک | ["Erbil", "Duhok"] |
marks = (78, 91, 65) | Round brackets make a tuple, which cannot be changedکەوانەی بازنەیی دروست دەکات، کە ناگۆڕدرێت | marks = [78, 91, 65] |
A variable named list بە ناوی list | list(...) stops working: TypeErrorlist(...) لە کار دەکەوێت: TypeError | Use another name, e.g. numbersناوێکی تر بەکار بهێنە، بۆ نموونە numbers |
x = x * 2 inside for x in a:x = x * 2 لە ناو for x in a: | The list does not change ناگۆڕێت | a[i] = a[i] * 2 |
value[5] = 80 for a list named valuesvalue[5] = 80 بۆ بە ناوی values | NameError | values[5] = 80 |
cities = ["Erbil" "Duhok", "Halabja"]
print(cities)
print(len(cities))['ErbilDuhok', 'Halabja'] 2
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Two strings written side by side are joined:
"ErbilDuhok".دوو کە لە تەنیشت یەکەوە نووسراون پێکەوە دەلکێن:
"ErbilDuhok".
list = [1, 2, 3]
letters = list("abc")Traceback (most recent call last):
File "shadow_list.py", line 2, in <module>
letters = list("abc")
^^^^^^^^^^^
TypeError: 'list' object is not callableExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
This hides the built-in
listclass behind your variable.ئەمە ئامادەی
listلە پشت دەشارێتەوە.- Lineدێڕی 2
Now
listis your list of numbers, which cannot be called.ئێستا
listناوی کە ژمارەی تێدایە و بانگ ناکرێت.
marks = (78, 91, 65)
print(type(marks))
marks[0] = 80<class 'tuple'>
Traceback (most recent call last):
File "tuple_not_list.py", line 3, in <module>
marks[0] = 80
~~~~~^^^
TypeError: 'tuple' object does not support item assignmentExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
A tuple, not a list: see Tuples, sets and dictionaries.
، نەک : بڕوانە تاپڵەکان، کۆمەڵەکان و فەرهەنگەکان.
Exercisesڕاهێنانەکان
Without running it, what does this print?
بەبێ جێبەجێکردن، ئەمە چی چاپ دەکات؟
days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[1], days[-1], days[len(days) - 2], days[-7])Show answerوەڵامەکە پیشان بدە
days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[1], days[-1], days[len(days) - 2], days[-7])Sun Fri Thu Sat
days[1] is the second day, "Sun". days[-1] is the last, "Fri". len(days) - 2 is 5, so days[5] is "Thu". The list has 7 elements, so days[-7] is the first, "Sat".
days[1] دووەم ڕۆژە، "Sun". days[-1] دوایینە، "Fri". len(days) - 2 یەکسانە بە 5، بۆیە days[5] دەبێتە "Thu". 7 هەیە، بۆیە days[-7] یەکەمیانە، "Sat".
Create a list with the marks 72, 85, 64, 90 and 58. Change the third mark to 70. Print the first mark and the last mark (use a negative index for the last one), then the whole list.
بە نمرەکانی 72، 85، 64، 90 و 58 دروست بکە. نمرەی سێیەم بگۆڕە بۆ 70. یەکەم نمرە و دوایین نمرە چاپ بکە (بۆ دوایینیان بەکار بهێنە)، پاشان هەموو .
Hintئاماژە
Third mark → index 2. Last element → index -1.
نمرەی سێیەم ← 2. دوایین ← -1.
Show answerوەڵامەکە پیشان بدە
marks = [72, 85, 64, 90, 58]
marks[2] = 70
print("First mark:", marks[0])
print("Last mark:", marks[-1])
print(marks)First mark: 72 Last mark: 58 [72, 85, 70, 90, 58]
The third mark has index 2, so it is marks[2], not marks[3].
نمرەی سێیەم 2ی هەیە، بۆیە marks[2]ـە، نەک marks[3].
cities = ["Erbil", "Sulaymaniyah", "Duhok", "Halabja"]. Print each city with its number, starting from 1. Write it twice: once with range(len(...)) and once with enumerate().
cities = ["Erbil", "Sulaymaniyah", "Duhok", "Halabja"]. هەر شارێک لەگەڵ ژمارەکەی چاپ بکە، لە 1ەوە. دوو جار بینووسە: جارێک بە range(len(...)) و جارێک بە enumerate().
Show answerوەڵامەکە پیشان بدە
range(len())ex_numbered_range.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەcities = ["Erbil", "Sulaymaniyah", "Duhok", "Halabja"]
for i in range(len(cities)):
print(i + 1, cities[i])1 Erbil 2 Sulaymaniyah 3 Duhok 4 Halabja
enumerate()enumerate_start.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەcities = ["Erbil", "Sulaymaniyah", "Duhok", "Halabja"]
for number, city in enumerate(cities, start=1):
print(number, city)1 Erbil 2 Sulaymaniyah 3 Duhok 4 Halabja
The index starts at 0, so the first version prints i + 1. The second lets enumerate() do the counting with start=1.
لە 0ەوە دەست پێ دەکات، بۆیە وەشانی یەکەم i + 1 چاپ دەکات. وەشانی دووەم ژماردنەکە بە start=1 دەداتە دەست enumerate().
Print the elements of a = [12, 5, 8, 4, 2, 0] from the last to the first, on one line. Find two ways.
a = [12, 5, 8, 4, 2, 0] لە دوایینەوە بۆ یەکەم، لە یەک دێڕدا چاپ بکە. دوو ڕێگە بدۆزەوە.
Hintئاماژە
range(start, stop, -1) counts down; [::-1] reverses a list.
range(start, stop, -1) بەرەو خوار دەژمێرێت؛ [::-1] پێچەوانە دەکاتەوە.
Show answerوەڵامەکە پیشان بدە
a = [12, 5, 8, 4, 2, 0]
for i in range(len(a) - 1, -1, -1):
print(a[i], end=" ")
print()
for x in a[::-1]:
print(x, end=" ")
print()0 2 4 8 5 12 0 2 4 8 5 12
Way 1 counts the indexes down from len(a) - 1 to 0 (range stops before -1). Way 2 loops over the reversed slice a[::-1], a new list.
ڕێگەی 1 لە len(a) - 1ەوە بەرەو خوار تا 0 دەژمێرێت (range پێش -1 دەوەستێت). ڕێگەی 2 بەسەر پێچەوانەی a[::-1]دا دەسووڕێتەوە، کە نوێیە.
Write a loop that prints every valid index of row = ["a", "b", "c", "d"], negative ones included, together with the element it reaches.
بنووسە کە هەموو دروستی row = ["a", "b", "c", "d"] چاپ بکات، سالبەکانیشەوە، لەگەڵ ئەو پێی دەگات.
Show answerوەڵامەکە پیشان بدە
row = ["a", "b", "c", "d"]
for i in range(-len(row), len(row)):
print(i, row[i])-4 a -3 b -2 c -1 d 0 a 1 b 2 c 3 d
For 4 elements the valid indexes are -4 to 3, which is range(-len(row), len(row)). Each element is reached twice: once from each end.
بۆ 4 ، لە -4 تا 3 دروستن، واتە range(-len(row), len(row)). هەر دوو جار دەگاتێ: جارێک لە هەر سەرێکەوە.
Summaryپوختە
- A list keeps many values in order under one name:
[2, "three", 4]. It can be empty and can mix types. []andlist()make lists;list()also turns arangeor a string into a list.len()counts the elements.- Unlike a fixed-size array, a Python list grows and shrinks.
values[i]reads or replaces one element. Indexes start at 0; for elements the valid indexes are to , anything else isIndexError.-1is the last element and-len(values)the first: Python adds the length to a negative index.- Lists are mutable; strings are immutable and hold only characters.
- A slice
values[a:b]is a new list. Loop over elements, overrange(len(...)), or withenumerate().
- چەندین بە ڕیز لە ژێر یەک ناودا هەڵدەگرێت:
[2, "three", 4]. دەکرێت بەتاڵ بێت و جۆرەکان تێکەڵ بکات. []وlist()دروست دەکەن؛list()هەروەهاrangeیان دەکات بە .len()دەژمێرێت.- بە پێچەوانەی قەبارە جێگیرەوە، لە گەورە و بچووک دەبێت.
values[i]یەک دەخوێنێتەوە یان دەیگۆڕێت. لە 0ەوە دەست پێ دەکەن؛ بۆ ، لە تا دروستن و هەر شتێکی ترIndexErrorـە.-1دوایین و-len(values)یەکەمیانە: درێژییەکە بۆ زیاد دەکات.- ؛ و تەنها هەڵدەگرن.
- وەک
values[a:b]نوێیە. بەسەر ، بەسەرrange(len(...))یان بەenumerate()بسووڕێوە.
a = [5, 6, 7]. What are a[0], a[-1] and len(a)?a = [5, 6, 7]. a[0]، a[-1] و len(a) چین؟
5, 7 and 3.
5، 7 و 3.
Name two differences between a list and a string.دوو جیاوازیی نێوان لیست و زنجیرەنووسە بڵێ.
A list holds any types, a string only characters; a list is mutable, a string is immutable.
هەر جۆرێک هەڵدەگرێت، تەنها ؛ و .
Why does print(values[7]) fail for a 7-element list?بۆچی print(values[7]) بۆ لیستێکی 7 دانەیی سەرناکەوێت؟
Its indexes are 0 to 6 (or -7 to -1); 7 is out of range, so Python raises IndexError.
0 تا 6ن (یان -7 تا -1)؛ 7 لە دەرەوەی سنوورەکەیە، بۆیە IndexError دروست دەکات.
When do you need range(len(a)) instead of for x in a?کەی range(len(a))ت پێویستە لەبری for x in a؟
When you must change elements (a[i] = ...) or need the position; enumerate() gives index and element together.
کاتێک دەبێت بگۆڕیت (a[i] = ...) یان شوێنەکەت پێویستە؛ enumerate() و پێکەوە دەدات.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
Making lists and reaching, changing and slicing their elements by index; later chapters remove elements and find where a value is.
دروستکردنی ، خوێندنەوە، گۆڕین و بە ؛ بەشەکانی دواتر لادەبەن و شوێنی دەدۆزنەوە.
Watch 0:00–7:10: making lists ([], [0] * 5, list(range()), list('Hello'), len), then index 0 and -1, changing an element and slicing with a step.
لە 0:00 تا 7:10 سەیر بکە: دروستکردنی ([]، [0] * 5، list(range())، list('Hello')، len)، پاشان 0 و -1، گۆڕینی و بە هەنگاو.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Adding to a List and Finding Itemsزیادکردن بۆ لیستێک و دۆزینەوەی دانەکان
Related lecturesوانە پەیوەندیدارەکان
- Adding to a List and Finding Itemsزیادکردن بۆ لیستێک و دۆزینەوەی دانەکان
- Removing Items, Joining and Comparing Listsلابردنی دانەکان، پێکەوەلکاندن و بەراوردکردنی لیستەکان
- Lists, References, Copies and Functionsلیستەکان، ئاماژەکان، کۆپی و کردارەکان
- The Python You Need for the AI Labsئەو Pythonـەی بۆ تاقیگەکانی ژیریی دەستکرد پێویستە
- Arrays in PHPڕیزەکەکان لە PHPـدا
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- The Python Tutorial, 3.1.3 Lists
- The Python Tutorial, 5. Data Structures (list methods, looping techniques)
- Python Standard Library: Built-in Types — common sequence operations and lists
- Python Standard Library: Built-in Functions (enumerate, len, list)
- Harvard CS50's Introduction to Programming with Python, Week 2 notes (lists and loops)
- Python Design and History FAQ: How are lists implemented in CPython?
- Python Standard Library: array — efficient arrays of numeric values
- PEP 8 — Style Guide for Python Code
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.