Lists are Mutable
""" LISTS - MUTABLE
-------------------
Unlike strings, lists are mutable.
A list contains multiple values in an ordered sequence.
-------------------------------------------------------
"""
A = [1, 2]
A = [3, 4] # mutable
A[1] = 5 # mutable
assert A == [3, 5]
assert A != [1, 2]
print('Tests passed')
Lists Concatenation
""" LISTS - CONCATENATION
-------------------------
To concatenate two list use + operator.
To multiply a list use * operator.
----------------------------------
"""
A = [1, 2] + [3,4] # concatenation
B = [9] * 4 # multiplication
C = [1, 2] * 2
assert A == [1, 2, 3, 4]
assert B == [9, 9, 9, 9]
assert C == [1, 2, 1, 2]
print('Tests passed')
Slice operator
""" SLICE operator [:]
----------------------
The slice operator works on list, as with strings.
The value -1 refers to the last index in a list.
------------------------------------------------
"""
a = "abcde"
assert a[:1] == "a"
assert a[1:] == "bcde"
assert a[1:3] == "bc" # limit 3 not included
A = [1, 2, 3, 4, 5]
assert A[:1] != 1
assert A[:1] == [1]
assert A[1:] == [2, 3, 4, 5]
assert A[1:3] == [2, 3] # limit 3 not included
assert A[-1] == 5
assert A[-1:] == [5] # last
print('Tests passed')
Append operator
""" LISTS - APPEND operator
--------------------------
To add an element to a list use append().
To add a list to another list use extend().
The del statement removes values at the index in a list.
--------------------------------------------------------
"""
A = ['a', 'b', 'c']
A.append('x')
assert A != ['a', 'b', 'c']
assert A == ['a', 'b', 'c', 'x']
B = ['d', 'e']
A.extend(B)
assert A != ['a', 'b', 'c']
assert A == ['a', 'b', 'c', 'x', 'd', 'e']
del A[3]
assert A != ['a', 'b', 'c', 'x', 'd', 'e']
assert A == ['a', 'b', 'c', 'd', 'e']
print('Tests passed')
Sorted operator
""" LISTS - SORTED operator
---------------------------
Return a sorted list of the specified iterable object.
Example:
- Find the students having the second lowest grade.
----------------------------------------------------
"""
records = [["John", 20.0], ["Ana", 50.0], ["Marry", 50.0], ["Bob", 50.2]]
scores = [s for n,s in records] # List comprehension
scores = set(scores) # Sets automatically remove duplicates
second_minim = sorted(scores)[1] # sorted, second
result = [
name
for name, score in records
if score == second_minim
]
print(second_minim) # 50
print(result) # [Ana, Marry]