☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

Lists

الأسبوع 7 · الدرس ٣ «السلاسل النصية والقوائم في لغة Python» (٢): القوائم والربط بين السلاسل والقوائم والبرامج التطبيقية · 3 دروس
1

Lists: many values in one variable

ICT Prep 3 Term 1, Unit 1, Lesson 3: pp. 34–42
GoalMake a list, read an item by its index, count the items and change one item.
New words
list · ordered values kept together in square bracketsitem · one value inside a listmutable · can be changed after it is madelen() · gives the number of items in a list
Explanation

A string holds characters. A list holds values of any kind, in order, between square brackets and separated by commas. The items of one list may be of different types: [7, "pen", 2.5, True]. Items are numbered like the characters of a string, from zero: names[0] is the first item, and len(names) counts the items. Here is the big difference from strings: a list can be changed. The line names[1] = "Adam" replaces the second item. A thing that can be changed after it is made is called mutable. Remember Week 6: a string cannot be changed, so text[0] = "S" failed, but a list accepts the change. The index rules are the same: the last valid index is the length minus one.

ABC
1MonaOmarSalma
2012
Worked examples
Python
1names = ["Mona", "Omar", "Salma"]
2print(names[0])
3print(len(names))
4names[1] = "Adam"
5print(names)
Output
Mona
3
['Mona', 'Adam', 'Salma']
Mona makes a list of three names. She reads the first item, counts the items and changes the second item. The printed list shows the new value. The index of the changed item did not move.
Python
1items = [7, "pen", 2.5, True]
2print(len(items))
3print(items)
Output
4
[7, 'pen', 2.5, True]
A list can hold different kinds of values at once: a whole number, a string, a decimal number and True. Its length is the number of items, 4.
Class activity

Make a list of five things in your school bag, written on paper. Write the index under each item. Which index is the last? Then change the third item and write the new list.

Practice
1
In names = ["Mona", "Omar", "Salma"], what is names[2]?
2
What is len([5, 8, 1, 9])?
3
Why does numbers[1] = 7 work on a list but text[1] = "a" fails on a string?
4
Can one list hold a number and a word together?