Python Tuples

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.




Cara Nggawe Tumpik

colorsTuple = ('red', 'green', 'blue') print(colorsTuple)

Output:

('red', 'green', 'blue')

Nggawe Tuple Kanthi Mung Siji Barang

Tuples mbutuhake paling ora siji koma, mula kanggo nggawe tuple kanthi mung siji item, sampeyan wis nambah koma sawise item kasebut. Contone:


colorsTuple = ('red',)

Cara Ngakses Barang saka Tuple

Kita bisa ngakses item tuple kanthi nuduhake nomer indeks:



colorsTuple = ('red', 'green', 'blue') print(colorsTuple[2])

Output:

blue

Ngakses Rentang Barang (Ngiris)

Kita bisa nemtokake macem-macem barang saka tuple kanthi nemtokake indeks wiwitan lan indeks pungkasan. Kita nggunakake : operator.

Cathetan:Nilai bali uga bakal dadi tuple karo barang sing ditemtokake. colorsTuple = ('red', 'green', 'blue', 'yellow', 'orange', 'white') print(colorsTuple[1:4])

Output:


('green', 'blue', 'yellow')

Indeks Negatif

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

Cara Loop Liwat Tuple

Kita bisa muter liwat tuple nggunakake for gelung

colorsTuple = ('red', 'green', 'blue', 'orange') for c in colorsTuple:
print(c)

Output:


red green blue orange

Cara Mbusak Tuple

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


Kepiye Cara Golek Panjang saka Tuple

Sampeyan bisa entuk dawa tuple kanthi nelpon len() fungsi, kayata:

colorsTuple = ('red', 'green', 'blue', 'orange') print(len(colorsTuple))

Output:


4

Cacah Jumlah Barang sing Ditemtokake

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 Nggabungake Rong Lekah

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)