Набір Python (з прикладами)

У цій статті ви дізнаєтеся все про кортежі Python. Точніше, що таке кортежі, як їх створювати, коли їх використовувати та різні методи, з якими ви повинні бути знайомі.

Відео: Списки та кортежі Python

Кортеж у Python подібний до списку. Різниця між ними полягає в тому, що ми не можемо змінити елементи кортежу, як тільки він призначений, тоді як ми можемо змінити елементи списку.

Створення кортежу

Кортеж створюється шляхом розміщення всіх елементів (елементів) усередині дужок (), розділених комами. Дужки не є обов’язковими, однак корисно використовувати їх.

Кортеж може мати будь-яку кількість елементів, і вони можуть бути різного типу (ціле число, плаваючий, список, рядок тощо).

 # 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)

Вихідні дані

 () (1, 2, 3) (1, 'Привіт', 3.4) ('миша', (8, 4, 6), (1, 2, 3))

Кортеж також можна створити без використання дужок. Це відоме як упаковка кортежу.

 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

Вихідні дані

 (3, 4.6, 'собака') 3 4.6 собака

Створення кортежу з одним елементом трохи складно.

Наявність одного елемента в дужках недостатньо. Нам знадобиться завершальна кома, щоб вказати, що насправді це кортеж.

 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)) # 

Вихідні дані

 

Доступ до порожніх елементів

Існують різні способи доступу до елементів кортежу.

1. Індексація

Ми можемо використовувати оператор індексу ()для доступу до елемента в кортежі, де індекс починається з 0.

Отже, кортеж, що має 6 елементів, матиме індекси від 0 до 5. Спроба отримати доступ до індексу поза діапазоном індексу кортежу (6,7,… у цьому прикладі) підніме значення IndexError.

Індекс повинен бути цілим числом, тому ми не можемо використовувати float чи інші типи. Це призведе до TypeError.

Так само до вкладених кортежів здійснюється доступ за допомогою вкладеного індексування, як показано в прикладі нижче.

 # 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

Вихідні дані

 очок 4

2. Негативне індексування

Python дозволяє негативне індексування своїх послідовностей.

Індекс -1 відноситься до останнього пункту, -2 до другого останнього пункту тощо.

 # 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))

Вихідні дані

 tp

3. Нарізка

Ми можемо отримати доступ до ряду елементів у кортежі за допомогою двокрапки оператора нарізки :.

 # 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(:))

Вихідні дані

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

Нарізання найкраще візуалізувати, враховуючи, що індекс знаходиться між елементами, як показано нижче. Отже, якщо ми хочемо отримати доступ до діапазону, нам потрібен індекс, який виріже частину з кортежу.

Нарізання елементів у Python

Зміна кортежу

На відміну від списків, кортежі незмінні.

Це означає, що елементи кортежу не можуть бути змінені після їх призначення. Але якщо сам елемент є змінним типом даних, як список, його вкладені елементи можна змінити.

Ми також можемо призначити кортеж різним значенням (перепризначення).

 # 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)

Вихідні дані

 (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:

  • Зазвичай ми використовуємо кортежі для різнорідних (різних) типів даних та списки для однорідних (подібних) типів даних.
  • Оскільки кортежі незмінні, ітерація через кортеж відбувається швидше, ніж у списку. Отже, невеликий приріст продуктивності.
  • Кортежі, що містять незмінні елементи, можуть бути використані як ключ для словника. У списках це неможливо.
  • Якщо у вас є дані, які не змінюються, реалізація їх як кортеж гарантуватиме, що вони залишаться захищеними від запису.

Цікаві статті...