Python Tuple (Örneklerle)

Bu makalede, Python tuples hakkında her şeyi öğreneceksiniz. Daha spesifik olarak, tuple nedir, nasıl oluşturulur, ne zaman kullanılır ve aşina olmanız gereken çeşitli yöntemler.

Video: Python Listeleri ve Tuples

Python'daki bir demet, bir listeye benzer. İkisi arasındaki fark, bir tuple atandıktan sonra elemanlarını değiştiremeyeceğimiz halde, bir listenin elemanlarını değiştirebileceğimizdir.

Bir Demet Oluşturma

Tüm öğeler (öğeler) (), virgülle ayrılmış olarak parantez içine yerleştirilerek bir demet oluşturulur . Parantezler isteğe bağlıdır, ancak bunları kullanmak iyi bir uygulamadır.

Bir demet herhangi bir sayıda öğeye sahip olabilir ve farklı türlerde olabilir (tamsayı, kayan nokta, liste, dize, vb.).

 # Different types of tuples # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple my_tuple = ("mouse", (8, 4, 6), (1, 2, 3)) print(my_tuple)

Çıktı

 () (1, 2, 3) (1, 'Merhaba', 3.4) ('fare', (8, 4, 6), (1, 2, 3))

Bir demet, parantez kullanılmadan da oluşturulabilir. Bu, tuple paketleme olarak bilinir.

 my_tuple = 3, 4.6, "dog" print(my_tuple) # tuple unpacking is also possible a, b, c = my_tuple print(a) # 3 print(b) # 4.6 print(c) # dog

Çıktı

 (3, 4.6, 'köpek') 3 4.6 köpek

Tek öğeli bir demet oluşturmak biraz karmaşıktır.

Parantez içinde bir öğe olması yeterli değildir. Aslında, bir demet olduğunu belirtmek için sondaki virgüllere ihtiyacımız olacak.

 my_tuple = ("hello") print(type(my_tuple)) # # Creating a tuple having one element my_tuple = ("hello",) print(type(my_tuple)) # # Parentheses is optional my_tuple = "hello", print(type(my_tuple)) # 

Çıktı

 

Tuple Öğelerine Erişim

Bir demetin öğelerine erişmenin çeşitli yolları vardır.

1. Endeksleme

()Dizinin 0'dan başladığı bir demetteki bir öğeye erişmek için dizin operatörünü kullanabiliriz .

Dolayısıyla, 6 elemanlı bir demet, 0'dan 5'e kadar indislere sahip olacaktır. Tuple indeks aralığı dışındaki bir indekse erişmeye çalışmak (bu örnekte 6,7,…) bir yükseltir IndexError.

Dizin bir tamsayı olmalıdır, bu nedenle float veya diğer türleri kullanamayız. Bu sonuçlanacaktır TypeError.

Benzer şekilde, aşağıdaki örnekte gösterildiği gibi, iç içe geçmiş kayıtlara iç içe dizin oluşturma kullanılarak erişilir.

 # Accessing tuple elements using indexing my_tuple = ('p','e','r','m','i','t') print(my_tuple(0)) # 'p' print(my_tuple(5)) # 't' # IndexError: list index out of range # print(my_tuple(6)) # Index must be an integer # TypeError: list indices must be integers, not float # my_tuple(2.0) # nested tuple n_tuple = ("mouse", (8, 4, 6), (1, 2, 3)) # nested index print(n_tuple(0)(3)) # 's' print(n_tuple(1)(1)) # 4

Çıktı

 puan 4

2. Negatif Endeksleme

Python, dizileri için negatif indekslemeye izin verir.

-1 indeksi son öğeye, -2 ikinci son öğeye ve bu böyle devam eder.

 # Negative indexing for accessing tuple elements my_tuple = ('p', 'e', 'r', 'm', 'i', 't') # Output: 't' print(my_tuple(-1)) # Output: 'p' print(my_tuple(-6))

Çıktı

 tp

3. Dilimleme

Dilimleme operatörünü iki nokta üst üste kullanarak bir demetteki çeşitli öğelere erişebiliriz :.

 # Accessing tuple elements using slicing my_tuple = ('p','r','o','g','r','a','m','i','z') # elements 2nd to 4th # Output: ('r', 'o', 'g') print(my_tuple(1:4)) # elements beginning to 2nd # Output: ('p', 'r') print(my_tuple(:-7)) # elements 8th to end # Output: ('i', 'z') print(my_tuple(7:)) # elements beginning to end # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple(:))

Çıktı

 ('r', 'o', 'g') ('p', 'r') ('i', 'z') ('p', 'r', 'o', 'g', 'r ',' a ',' m ',' i ',' z ')

Dilimleme, indeksin aşağıda gösterildiği gibi öğeler arasında olduğu düşünülerek en iyi şekilde görselleştirilebilir. Dolayısıyla, bir aralığa erişmek istiyorsak, bölümü tuple'dan ayıracak dizine ihtiyacımız var.

Python'da Eleman Dilimleme

Bir Demeti Değiştirme

Listelerden farklı olarak, demetler değişmezdir.

Bu, bir demet elemanının atandıktan sonra değiştirilemeyeceği anlamına gelir. Ancak öğenin kendisi liste gibi değiştirilebilir bir veri türü ise, iç içe geçmiş öğeleri değiştirilebilir.

Ayrıca farklı değerlere bir demet atayabiliriz (yeniden atama).

 # Changing tuple values my_tuple = (4, 2, 3, (6, 5)) # TypeError: 'tuple' object does not support item assignment # my_tuple(1) = 9 # However, item of mutable element can be changed my_tuple(3)(0) = 9 # Output: (4, 2, 3, (9, 5)) print(my_tuple) # Tuples can be reassigned my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple)

Çıktı

 (4, 2, 3, (9, 5)) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

We can use + operator to combine two tuples. This is called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result in a new tuple.

 # Concatenation # Output: (1, 2, 3, 4, 5, 6) print((1, 2, 3) + (4, 5, 6)) # Repeat # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3)

Output

 (1, 2, 3, 4, 5, 6) ('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple

As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.

Deleting a tuple entirely, however, is possible using the keyword del.

 # Deleting tuples my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # can't delete items # TypeError: 'tuple' object doesn't support item deletion # del my_tuple(3) # Can delete an entire tuple del my_tuple # NameError: name 'my_tuple' is not defined print(my_tuple)

Output

 Traceback (most recent call last): File "", line 12, in NameError: name 'my_tuple' is not defined

Tuple Methods

Methods that add items or remove items are not available with tuple. Only the following two methods are available.

Some examples of Python tuple methods:

 my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # Output: 2 print(my_tuple.index('l')) # Output: 3

Output

 2 3

Other Tuple Operations

1. Tuple Membership Test

We can test if an item exists in a tuple or not, using the keyword in.

 # Membership test in tuple my_tuple = ('a', 'p', 'p', 'l', 'e',) # In operation print('a' in my_tuple) print('b' in my_tuple) # Not in operation print('g' not in my_tuple)

Output

 True False True

2. Iterating Through a Tuple

We can use a for loop to iterate through each item in a tuple.

 # Using a for loop to iterate through a tuple for name in ('John', 'Kate'): print("Hello", name)

Output

 Hello John Hello Kate

Advantages of Tuple over List

Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:

  • Genelde heterojen (farklı) veri türleri için tuple ve homojen (benzer) veri türleri için listeler kullanırız.
  • Tuplelar değişmez olduğundan, bir demet boyunca yineleme, listeden daha hızlıdır. Yani hafif bir performans artışı var.
  • Değişmez öğeler içeren demetler, bir sözlük için anahtar olarak kullanılabilir. Listelerle bu mümkün değildir.
  • Değişmeyen verileriniz varsa, onu tuple olarak uygulamak, yazma korumalı kalmasını garanti edecektir.

Ilginç makaleler...