Creating and indexing
fruits = ["mango", "litchi", "guava"] print(fruits[0]) print(fruits[-1]) print(len(fruits))
Write Python. Understand every error.
Python basics · topic 11 of 25
A list stores many values in order, inside square brackets. Like strings, lists are indexed from 0.
marks = [72, 85, 90, 64] print(marks[0], marks[-1], len(marks))
Unlike strings, lists can be changed. append() adds an item to the end, insert() adds at a position, remove() deletes a value, and pop() removes and returns an item.
Built-in functions such as sum(), max(), min() and sorted() work on lists of numbers. A for loop visits every item in turn.
nums.append(5) adds 5 at the endnums.sort() sorts the list itself and returns Nonesorted(nums) gives a new sorted listx in nums checks membershipappend adds at the end and pop removes and returns the last item.nums.sort() sorts the list itself and returns None, while sorted(nums) returns a new sorted list.-1 is the last item. A slice such as nums[1:4] gives positions 1 to 3.sum(), max(), min() and len() work on lists of numbers.nums[3] in a list of three items. Read the IndexError guide.print(nums.sort()), which prints None.nums.push(5). In Python it is append. Read the AttributeError guide.
fruits = ["mango", "litchi", "guava"] print(fruits[0]) print(fruits[-1]) print(len(fruits))
nums = [4, 1, 7] nums.append(9) nums.insert(0, 2) nums.remove(1) print(nums) nums.sort() print(nums)
marks = [72, 85, 90, 64] print(sum(marks), max(marks), min(marks)) print(sorted(marks, reverse=True))
prices = [20, 35, 15] total = 0 for p in prices: total += p print("added", p) print("total", total)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
a = [10, 20, 30] a.append(40) print(len(a), a[-1])
append adds 40 to the end, so there are 4 items and the last is 40.
a = [3, 1, 2] b = sorted(a) print(a, b)
sorted() returns a new sorted list and leaves the original unchanged.
a = [1, 2, 3, 4, 5] print(a[1:4])
The slice takes indexes 1, 2 and 3.
a = [5, 3, 8] print(a.sort())
.sort() changes the list itself and returns None. Print the list afterwards instead.
nums = [2, 4, 6] print(sum(nums) / len(nums))
sum is 12, there are 3 items, and / always gives a float.