Video:
Innhold:
Iterere over elementer. (Datainnhold.)
liste1 = ['knut', 'fredik', 'aage'] for x in liste: print(x)
Iterere over indekser:
liste1 = ['knut', 'fredik', 'aage'] for inx in range(len(liste1)): print(inx) # 0, 1, 2 print(liste1[inx]) # knut, fredrik, aage
Iterere over indekser. Sette alle elementene i en liste til 0:
list1 = [1, 2, 3, 4] for inx in range(len(list1)): list1[inx] = 0 print(list1) print() # [0, 2, 3, 4] # # [0, 0, 3, 4] # # [0, 0, 0, 4] # # [0, 0, 0, 0]
Printe to elementer pr linje. Hindre at index kjører «out of range»:
list1 = [1, 2, 3, 4, 5] for inx in range(0, len(list1), 2): if inx == len(list1) -1: print(list1[inx]) else: print(list1[inx], list1[inx] + 1) # 1 2 # 3 4 # 5