Python. Operations on tuples. Bypass of tuple. Methods of working with tuples.




Operations on tuples. Bypass of tuple. Methods of working with tuples


Contents


Search other websites:

1. Tuple assignment operation =. Examples

Any object with a name can be assigned a tuple. Examples of assignment of tuples.

a = () # empty tuple
b = (5,'Hello', True) # tuple of 3 elements of various types
c = ('world', (2.88, "bestprog")) # nested tuple
d = 5, 'Hello', True # same tuple as b
e = (3.88,) # Tuple strictly from one element

 

2. Operation tuple() – creating a tuple from an iterable object

A tuple can be created using the tuple() operation. This operation takes an iterated object as a parameter, which can be another tuple, list, string. For example

# Operation tuple()
# 1. Creating a tuple from the word 'Hello'
d = tuple('Hello'); # d = ('H', 'e', 'l', 'l', 'o')

# 2. Creating a tuple from a list
# Specified list
lst = [2, "abc", 3.88]

# Create a tuple
e = tuple(lst) # e = (2, 'abc', 3.88)

# 3. Create a tuple from another tuple
f = tuple((3, 2, 0, -5)) # f = (3, 2, 0, -5)

 

3. Operation T[i]. Creating a tuple from another tuple

A tuple element can be obtained by index.

Example.

# Tuples. The operation of taking the index
# 1. Tuple containing strings
a = ('a', 'bc', 'def', 'ghij')
item = a[2] # item = 'def'

# 2. A tuple containing another tuple and its elements
b = (a, a[1], True)
item = b[0] # item = ('a', 'bc', 'def', 'ghij')
item = b[1] # item = 'bc'

# 3. Tuple containing a list
c = (1, [2, 3, 4], "text")

# 3.1. Get list from tuple
item = c[1] # item = [2, 3, 4], с =   (1, [2, 3, 4], 'text')

# 3.2. The list in the tuple is mutable, so it can be changed
c[1][1] = 8 # с = (1, [2, 8, 4], 'text')

 



4. Operation T[i][j]. Get access to the constituent elements in a tuple

 As you know, a tuple can contain nested objects, which can be lists, strings, or even other tuples. To get an element of a nested object, you need to use the index take operation

T[i][j]

where

  • T – name of the tuple;
  • i – the position of the nested object in the tuple;
  • j – position of the element in the nested object.

Пример.

# Operation T[i][j] - get an element by index
# 1. Tuple that contains the list
A = ( 2.5, ['a', True, 3.17], 8, False, 'z')
item1 = A[1]   # item1 =   ['a', True, 3.17]
item2 = A[1][2] # item2 = 3.17

# 2. Tuple that contains the list
B = ( "Hello", "abcd", 2.55)
item1 = B[0]   # item1 =   'Hello'
item2 = B[0][4] # item2 = 'o'

# 3. A tuple that contains another tuple, list, string
C = ( (1, 2, 5), [2, 7, -100], "Python")
item1 = C[0]   # item1 =   (1, 2, 5)
item2 = C[0][2] # item2 = 5

# 4. Three investment levels
D = ( [ 7, True, ('a', 'b', 'cd')], 12, "bestprog")
item1 = D[0]       # item1 =   [7, True, ('a', 'b', 'cd')]
item2 = D[0][2]   # item2 =   ('a', 'b', 'cd')
item3 = D[0][2][1] # item2 = 'b'

 

5. Operation T[i:j] taking a slice in a tuple

Using the operation of taking the slice, you can get another tuple. The general form of a tuple slice operation is as follows

T2 = T1[i:j]

here

  • T2 – A new tuple, which is obtained from the tuple T1;
  • T1 – the initial tuple for which the slice occurs;
  • i, j – respectively, the lower and upper boundaries of the slice. In fact, elements placed at positions i, i+1, …, j-1 are taken into account. The value j determines the position after the last element of the slice.

The operation of taking a slice for a tuple may have modifications. For more information on using slices in Python, see the topic:

Example.

# Operation [i:j] - taking a slice
# 1. Tuple containing integers
A = ( 0, 1, 2, 3)
item = A[0:2]   # item =   (0, 1)

# 2. Tuple containing list
A = ( 2.5, ['abcd', True, 3.1415], 8, False, 'z')
item = A[1:3] # item = (['abcd', True, 3.1415], 8)

# 3. A tuple containing a nested tuple
A = (3, 8, -11, "program")
B = ("Python", A, True)
item = B[:3] # item = ('Python', (3, 8, -11, 'program'), True)
item = B[1:] # item = ((3, 8, -11, 'program'), True)

 

6. Concatenation +

For tuples, you can perform the concatenation operation, which is indicated by the + symbol. In the simplest case, to concatenate two tuples, the general form of the operation is as follows

T3 = T1 + T2

where

  • T1, T2 – tuples for which you want to perform the concatenation operation. The operands T1, T2 must be tuples. When performing the concatenation operation for tuples, it is forbidden to use any other types (strings, lists) as operands;
  • T3 – the tuple that is the result.

Example.

# Tubpes. Concatenation +
# Concatenation of two tuples
A = (1, 2, 3)
B = (4, 5, 6)
C = A + B # C =   (1, 2, 3, 4, 5, 6)

# Concatenation of tuples with complex objects
D = (3, "abc") + (-7.22, ['a', 5]) # D = (3, 'abc', -7.22, ['a', 5])

# Concatenation of three tuples
A = ('a', 'aa', 'aaa')
B = A + (1, 2) + (True, False) # B = ('a', 'aa', 'aaa', 1, 2, True, False)

 

7. Reiteration *

A tuple can be formed by a repetition operation indicated by *. When used in an expression, the general form of the operation is as follows

T2 = T1 * n

here

  • T2 – resulting tuple;
  • T1 – original tuple, which must be repeated n times;
  • n – the number of repetitions of the tuple T1.

Example.

# Tuples. Reiteration *
# A tuple that contains integers
A = (1, 2, 3) * 3 # A = (1, 2, 3, 1, 2, 3, 1, 2, 3)

# A tuple that contains nested objects
B = ("ab", ["1", "12"])*2 # A=('ab', ['1','12'], 'ab', ['1','12'])

 

8. Bypass a tuple in a loop. Example

Tuple elements can be sequentially viewed using while or for loop statements.

Example

# Bypass tuple in the cycle
# 1. for loop
# Specified tuple
A = ("abc", "abcd", "bcd", "cde")

# Print all tuple elements
for item in A:
    print(item)

# 2. while loop
# Print all tuple elements
A = (-1, 3, -8, 12, -20)

# Calculate the number of positive numbers
i = 0
k = 0 # number of positive numbers

while i < len(A):
    if (A[i]<0):
        k = k + 1
    i = i + 1

# Display the result
print("k = ", k)

# 3. Using for loop
# The specified tuple containing the strings
A = ("abc", "ad", "bcd")

# Form a new list of elements of tuple A,
# in the new list B, each element is doubled
B = [item * 2 for item in A]

print("A = ", A)
print("B = ", B)

The result of the program

abc
abcd
bcd
cde
k = 3
A = ('abc', 'ad', 'bcd')
B = ['abcabc', 'adad', 'bcdbcd']

 

9. Operation in. Checking the occurence of element in a tuple
# Checking the occurence of an element in a tuple
# Operation in
# The specified tuple that contains a strings
A = ("abc", "abcd", "bcd", "cde")

# input an item
item = str(input("s = "))

if (item in A):
    print(item, " in ", A, " = True")
else:
    print(item, " in ", A, " = False")

The result of the program

s = abc
abc in   ('abc', 'abcd', 'bcd', 'cde') = True

 

10. Methods for working with tuples
10.1. Method index(). Search for the item’s position in the tuple

To get the index (position) of an element in a tuple, you need to use the index() method. The general form of the method call is as follows

pos = T.index(item)

where

  • T – tuple in which the search is performed;
  • pos – the position (index) of the item in the tuple. The first element corresponds to position 0. If the element is not in the tuple, an exception is thrown. Therefore, it is recommended to check for the presence of an element (using the in operation) before using the index() method.

Example. The example calculates the day ordinal.

# Index method - determines the position (index) of an element in a tuple
# Specified tuple
A = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")

# Request to enter the name of the day of the week
day = str(input("Enter day: "))

# Correctly calculate the index
if day in A: # check whether there is a day in the tuple A
    num = A.index(day)
    print("Number of day = ", num + 1)
else:
    num = -1
    print("Wrong day.")

The result in the program

d = 1

 

10.2. Method count(). Determine the number of occurrences of a given element in a tuple

To determine the number of occurrences of a given element in a tuple, the count method is used, the general form of which is as follows:

k = T.count(item)

here

  • T – original tuple;
  • k – result (number of items);
  • item – the element whose number of occurrences is to be determined. An element can be composite (string, list, tuple).

 

# Method count - count the number of occurrences of an element in a tuple
# Specified tuple
A = ("ab", "ac", "ab", "ab", "ca", "ad", "jklmn")

d1 = A.count("ab")   # d1 = 3
d2 = A.count("jprst") # d2 = 0
d3 = A.count("ca")   # d3 = 1

print("d1 = ", d1)
print("d2 = ", d2)
print("d3 = ", d3)

The result of the program

d1 = 3
d2 = 0
d3 = 1

 


Related topics