En liten demo
# Mutable type: list
L = [1, 2, 3, 4, 5, 6, 7, 8]
# Sjekk hvilken type L har:
type(L)
# lister har en del innebygde metoder. Vi kan liste ut disse med dir-funksjonen:
dir(L)
Metoder med navn som starter og slutter med dobbel understrek (dunder methods - Double UNDER), er ikke ment å brukes direkte. De som har normale navn kan kalles med prikk-notasjon, f.eks. L.reverse()
print(L.reverse())
print(L)
Lista L er mutert.
# Immutable type: str
S = "red moon"
type(S)
dir(S)
print(S.upper())
SU = S.upper()
print(SU)
LR = L.reverse()
print(LR)
print(L)
# Med id() kan vi sjekke objekt-id'en:
S2 = S.title()
print(S)
print(S2)
print(id(S))
print(id(S2))
L2 = L
L2.reverse()
print(L)
print(L2)
print(id(L))
print(id(L2))
# Haltermann, Richard L. 2019. Fundamentals of Python Programming
# Listing 10.15: listequivalence.py
# a and b are distinct lists that contain the same elements
a = [10, 20, 30, 40]
b = [10, 20, 30, 40]
print('Is ', a, ' equal to ', b, '?', sep='', end=' ')
print(a == b)
print('Are ', a, ' and ', b, ' aliases?', sep='', end=' ')
print(a is b)
# c and d alias are distinct lists that contain the same elements
c = [100, 200, 300, 400]
d = c
# Makes d an alias of c
print('Is ', c, ' equal to ', d, '?', sep='', end=' ')
print(c == d)
print('Are ', c, ' and ', d, ' aliases?', sep='', end=' ')
print(c is d)
# Haltermann, Richard L. 2019. Fundamentals of Python Programming
# Listing 10.16: listcopy.py
def list_copy(lst):
result = []
for item in lst:
result += [item]
return result
def main():
# a and b are distinct lists that contain the same elements
a = [10, 20, 30, 40]
b = list_copy(a)
# Make a copy of a
print('a =', a, ' b =', b)
print('Is ', a, ' equal to ', b, '?', sep='', end=' ')
print(a == b)
print('Are ', a, ' and ', b, ' aliases?', sep='', end=' ')
print(a is b)
b[2] = 35
# Change an element of b
print('a =', a, ' b =', b)
main()