1-D arrays (lists) · مصفوفات 1-D (قوائم)
A list holds many values
- A list (the exam calls it an array) stores many values under one name.
- Write the items in square brackets, separated by commas.
- An array normally stores items of the same type.
القائمة تحتوي على قيم متعددة
- القائمة (تُطلق عليها الامتحانات المصفوفة) تخزن قيمًا متعددة تحت اسم واحد.
- اكتب العناصر بين أقواس مربعة، مفصولة بفاصلة.
- تخزن المصفوفة عادةً عناصر من نفس النوع.
scores = [40, 55, 72, 90]
print(scores)
Reach an item by its index
- Each item has a position number called its index.
- Python counts from 0, so the first item is
scores[0].
الوصول إلى عنصر عن طريق فهرسه
- لكل عنصر رقم موقع يُسمى فهرسه (Index).
- يبدأ بايثون العد من 0، لذا فإن العنصر الأول هو
scores[0].
scores = [40, 55, 72, 90]
print(scores[0]) # 40
print(scores[2]) # 72
Index and change a list · الفهرسة وتغيير قائمة
Items are numbered from 0; scores[0] is the first item. · العناصر مرقّمة بدءًا من 0؛ لذا فإن scores[0] هو العنصر الأول.
Change an item
- Assign to an index to replace that one item.
تغيير عنصر
- قم بتعيين قيمة لفهرس معين لاستبدال ذلك العنصر.
scores = [40, 55, 72, 90]
scores[1] = 99
print(scores) # [40, 99, 72, 90]
Length and looping
len(scores)gives how many items there are.- A
forloop visits each item in turn.
الطول والتكرار
len(scores)يعطيك عدد العناصر الموجودة.- حلقة
forتزور كل عنصر على التوالي.
scores = [40, 55, 72, 90]
print(len(scores)) # 4
for s in scores:
print(s)
In the exam: arrays start at 1
- Pseudocode declares an array with a size, and usually counts from 1.
في الامتحان: تبدأ المصفوفات من 1
- يُعلن الوصف الكاذب المصفوفة بحجم معين، وعادة ما يبدأ العد من 1.
DECLARE Scores : ARRAY[1:4] OF INTEGER
Scores[1] ← 40
OUTPUT Scores[1]
Common mistakes
- Index from
0; the last item is at positionlength - 1. - Going past the end gives an index error.
أخطاء شائعة
- الفهرس يبدأ من
0؛ العنصر الأخير يقع في الموقعlength - 1. - تجاوز النهاية يؤدي إلى خطأ في الفهرسة.
Now you try
- Use an index, or a loop, on each list.
- Press Check answer to test your code.
الآن جرب بنفسك
- استخدم فهرساً أو حلقة تكرار على كل قائمة.
- اضغط على تحقق من الإجابة لاختبار الكود الخاص بك.
The list colours is set for you. Store its second item in a variable called second (remember Python counts from 0). · القائمة colours مُعددة مسبقًا. ذخّر عنصرها الثاني في متغير اسمه second (تذكر أن بايثون يبدأ العدّ من 0).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Change the first item of the list nums to 99. · غيّر العنصر الأول في القائمة nums إلى 99.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Use a loop to add up every number in nums and store the result in total (the answer is 43). · استخدم حلقة لجمع كل رقم في nums وتخزين النتيجة في total (الإجابة هي 43).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.