Ing Python, tuple minangka koleksi yaiku dipesen lan ora owah . Iki tegese kita ora bisa nambah utawa mbusak item saka tuple.
Kita nggawe tuple nggunakake kurung ()
lan paling ora siji koma ( , )
.
Tuples bisa diindeks lan diiris kaya dhaptar, kajaba asil irisan uga bakal dadi tuple.
colorsTuple = ('red', 'green', 'blue') print(colorsTuple)
Output:
('red', 'green', 'blue')
Tuples mbutuhake paling ora siji koma, mula kanggo nggawe tuple kanthi mung siji item, sampeyan wis nambah koma sawise item kasebut. Contone:
colorsTuple = ('red',)
Kita bisa ngakses item tuple kanthi nuduhake nomer indeks:
colorsTuple = ('red', 'green', 'blue') print(colorsTuple[2])
Output:
blue
Kita bisa nemtokake macem-macem barang saka tuple kanthi nemtokake indeks wiwitan lan indeks pungkasan. Kita nggunakake :
operator.
colorsTuple = ('red', 'green', 'blue', 'yellow', 'orange', 'white') print(colorsTuple[1:4])
Output:
('green', 'blue', 'yellow')
Kita bisa ngakses item ing tuple saka pungkasan kanthi nemtokake nilai indeks negatif. Contone -1
tegese barang pungkasan lan -2
tegese barang pungkasan nomer loro.
colorsTuple = ('red', 'green', 'blue', 'yellow', 'orange', 'white') print(colorsTuple[-2])
Output:
orange
Kita bisa muter liwat tuple nggunakake for
gelung
colorsTuple = ('red', 'green', 'blue', 'orange') for c in colorsTuple:
print(c)
Output:
red green blue orange
Kanggo mbusak tuple kanthi lengkap, gunakake del
tembung kunci
colorsTuple = ('red', 'green', 'blue', 'orange') del colorsTuple print(colorsTuple)
Output
Traceback (most recent call last): File 'pythonTuples.py', line 98, in
print(colorsTuple) NameError: name 'colorsTuple' is not defined
Sampeyan bisa entuk dawa tuple kanthi nelpon len()
fungsi, kayata:
colorsTuple = ('red', 'green', 'blue', 'orange') print(len(colorsTuple))
Output:
4
Kita bisa nggunakake count()
fungsi ing tupel kanggo entuk jumlah kedadeyan item sing ditemtokake ing tuple kasebut. Contone:
colorsTuple = ('red', 'green', 'blue', 'orange', 'red') print(colorsTuple.count('red'))
Output:
2
Cara paling gampang kanggo nggabungake rong tuple yaiku nggunakake +
operator. Contone:
colorsTuple = ('red', 'green', 'blue', 'orange') numbersTuple = (1, 2, 3, 4) numbersAndColors = colorsTuple + numbersTuple print(numbersAndColors)
Output:
('red', 'green', 'blue', 'orange', 1, 2, 3, 4)