List Operations, Functions and Methods
This is a free course. Log in to run the code exercises and track your progress.
List Operations, Functions and Methods
A list is a mutable, ordered sequence. It supports concatenation (+), repetition (*), membership (in) and slicing, just like a string, and its elements can be changed in place.
- Built-in functions:
len(),list(),min(),max(),sum(),sorted()(returns a new sorted list). - Methods that change the list:
append(),extend(),insert(),remove(),pop(),reverse(),sort(). - Methods that only look:
count(),index().
a = [3, 1, 2]
b = sorted(a) # a is unchanged: [3, 1, 2]; b is [1, 2, 3]
a.sort() # a itself is now [1, 2, 3]; sort() returns None
a.extend([5, 4]) # [1, 2, 3, 5, 4]
a.append([6]) # [1, 2, 3, 5, 4, [6]]: one element, a list
m = [[1, 2], [3, 4]]
print(m[1][0]) # 3: nested list, row 1, column 0
Because lists are mutable, b = a does not copy the list: both names refer to one list. Use a.copy(), list(a) or a[:] for a real copy.
Read a line of integers. Print the maximum, the minimum and the mean (two decimals) on one line separated by spaces, without using max(), min() or sum().
nums = list(map(int, input().split()))
big = small = nums[0]
total = 0
for n in nums:
pass # update big, small and total
print(big, small, f"{total / len(nums):.2f}")Log in to edit and run this code.