Juurdepääs elementidele ja operatsioonid ennikutel¶
Ennikus olevaid elemente saab kätte indeksi järgi []
operaatoriga. Indekseerimine algab 0
-st.
a_tuple = ("January", "February", "March")
# Index 0 1 2
print(a_tuple[0]) # -> January
print(a_tuple[2]) # -> March
# Tuple from a string
b_tuple = tuple("Technology") # -> ('T', 'e', 'c', 'h', 'n', 'o', 'l', 'o', 'g', 'y')
print(b_tuple[0]) # -> T
print(b_tuple[4]) # -> n
print(b_tuple[9]) # -> y
# Tuple index must be of type int. The range of index of tuple starts from 0 and ends at the length of tuple - 1.
print(b_tuple[10]) # -> IndexError: tuple index out of range
Python lubab kasutada negatiivset indekseerimist nii järjendites kui ka ennikutes.
-1
viitab viimasele elemendile, -2
eelviimasele jne.
c_tuple = ("n", "i", "c", "e")
print(c_tuple[-1]) # -> e
print(c_tuple[-2]) # -> c
Tükeldamise (slice) abil saab ligi kindlale vahemikule ennikus, sarnaselt paljudele teistele andmetüüpidele.
Tükeldamine toimub kasutades nurksulge ja koolonit: [start:stop:step]
.
[start]
indeks, kust alustada tükeldamist; selle ärajätmisel eeldab Python, et tükeldamine algab algusest[stop]
elemendi indeks, kus peatuda, kusjuures seda elementi ei arvata vahemikku; vaikimisi viimase elemendini[step]
sammu suurus itereerimisel, vaikimisi on see1
;-1
itereerib elemendid tagurpidi
c_tuple = ("a", "b", "c", "d")
# Range of elements between index 0 and index 2, element at index 2 is excluded
print(c_tuple[0:2]) # -> ('a', 'b')
# [start] can be omitted
print(c_tuple[:2]) # -> ('a', 'b')
print(c_tuple[2:4]) # -> ('c', 'd')
# [stop] can be omitted
print(c_tuple[2:]) # -> ('c', 'd')
# Slicing from start to end, easy way to make a copy
print(c_tuple[:]) # -> ("a", "b", "c", "d")
# By choosing [step] to be -1, we get the reverse of original
print(c_tuple[::-1]) # -> ('d', 'c', 'b', 'a')
Enniku puhul saab kasutada in
operaatorit, et kontrollida elemendi olemasolu ennikus.
tup = (123, "hello", 999)
b = "hello" in tup
print(b) # -> True