Min menu

Pages

Tuple in Python

 Classes tuplein Python

The tupleis an array of fixed size, it can store values ​​of different types simultaneously and its values ​​cannot be swapped.


method of definitiontuple 

To define tuplewe use the symbol ( ).
Inside this code you can pass values ​​directly to it provided you put a comma between every two elements. And you can only specify the type and number of items you want to put in it.


In the following example, we have defined tupleempty, that is, it does not contain any element.

first example

Test.py
A = () # A is an empty tuple named here we have defined
		  print(A) # (that is, as we defined it) as A Here we have shown what the object contains
	

We will get the following result when running.

()


In the following example, we have defined tuplea single element.

second example

Test.py
A = (10,) # consists of one element whose value is 10 tuple Here we have defined
		  print(A) # (that is, as we defined it) as A Here we have shown what the object contains
	

We will get the following result when running.

(10)

Whatch out

Putting a comma after the value 10 here is mandatory so that the Python interpreter understands that you intend to declare tupleand not a regular variable of 10 .
Also, there is no need to put an extra comma as we did here in case it wasthetuplecontains more than one value.



In the following example, we have defined tupleand put integers in it.

third example

Test.py
numbers = (10, 20, 30, 40, 50) # contains integers only numbers whose name is a tuple here we have defined
		  print(numbers) # ( as we defined it ) as numbers Here we have displayed the content of the object
	

We will get the following result when running.

(10, 20, 30, 40, 50)


In the following example, we have defined tupleand placed text in it.

Fourth example

Test.py
names = ('Rami', 'Sara', 'Nada') # contains text-only names whose name is a tuple here we have defined
		  print(names) # (that is, as we defined it) as it is names Here we have shown what the object contains
	

We will get the following result when running.

('Rami', 'Sara', 'Nada')


In the following example, we have defined tupleand put integers and texts in it.

Fifth example

Test.py
data = (1, 'Mhamad', 'Harmush', 1500) # contains integers and text data named tuple here we have defined
		  print(data) # (that is, as we defined it) as data Here we have shown what the object contains
	

We will get the following result when running.

(1, 'Mhamad', 'Harmush', 1500)

 Accessing Objects tuplein Python

To access any element in the in tupleorder to get its value, of course, we use the number ofIndexof the element.

How to access tuple elements in Python To access any element in the tuple in order to obtain its value, of course, we use the element's index number.

In Python, you can access elements inthetupleIn two ways:

  • If you want to access itemsthetupleFrom left to right, i.e. of the first element entered, theIndexFor the first element it will be 0 .

  • If you want to access itemsthetupleFrom right to left, i.e. of the last element entered, theIndexThe last element will be 1- .



In the following example, we have defined tupleand placed text in it. Then we display the value of the first and second element in it.

first example

Test.py
# We put text values ​​in it that represent names of people whose name is a tuple. Here we have defined
		  names = ('Rami', 'Sara', 'Nada', 'Mhamad', 'Salem')
	  
		  print(names[0]) # names Here we have shown the value of the first element found in the object
		  print(names[1]) # names Here we have shown the value of the second element in the object
	

We will get the following result when running.

Rami
Sara


In the following example, we have defined tupleand placed text in it. Then we display another value and before the last element in it.

second example

Test.py
# We put text values ​​in it that represent names of people whose name is a tuple. Here we have defined
		  names = ('Rami', 'Sara', 'Nada', 'Mhamad', 'Salem')
	  
		  print(names[-1]) # names Here we have shown the value of the last element found in the object
		  print(names[-2]) # names Here we have shown the value before the last element of the object
	

We will get the following result when running.

Salem
Mhamad


In the following example, we have defined tupleand placed text in it. Then we display all the values ​​placed in it using the loop for.

third example

Test.py
# We put text values ​​in it that represent names of people whose name is a tuple. Here we have defined
		  names = ('Rami', 'Sara', 'Nada', 'Mhamad', 'Salem')
	  
		  # and then x will be printed in the variable names every time the value of an object is set
		  for x in names:
		  print(x)
	

We will get the following result when running.

Rami
Sara
Nada
Mhamad
Salem


In the following example, we have defined tupleand put integers in it. Then we calculated the sum of all the values ​​placed in it using the loop for.

Fourth example

Test.py
# We put integer numbers in it called tuple Here we have defined
		  numbers = (10, 20, 30, 40, 50)
	  
		  # numbers Here we have defined a variable that we will use to save the sum of the values ​​in the object
		  total = 0
	  
		  # total and then it will be added to the value of the variable x in the variable numbers every time the value of an element of the object will be set
		  for x in numbers:
		  total += x
	  
		  # numbers which will be equal to the sum of the values ​​in the total object here we have printed the value of the variable
		  print('Total sum is:', total)
	

We will get the following result when running.

Total sum is: 150

fragmentationthetuplein python

What is meant by fragmentation?thetupleIt is the return of a part of it whether to display or store.


In the following example we have defined tupleand placed numbers in it. Then we showed part of it.
We actually displayed the items in it starting with the item that ownsIndexNumber 0 down to the element before the one that ownsIndexNo. 3 .
That is, we displayed the values ​​of the elements arr[0]- arr[1]- arr[2].

first example

Test.py
arr = (10, 20, 30, 40, 50) # we put integers in it arr named tuple here we define
	  
		  print(arr[0: 3]) # arr Here we have shown the first three elements of the object
	

We will get the following result when running.

(10, 20, 30)


In the following example we have defined tupleand placed numbers in it. Then we copied part of it and put it in tuplea second.
We actually copied the elements in it starting from the one that ownsIndexNumber 0 down to the element before the one that ownsIndexNo. 3 .
That is, we copied the values ​​of the elements arr[0]- arr[1]- arr[2].

second example

Test.py
arr = (10, 20, 30, 40, 50) # we put integers in it arr named tuple here we define
	  
		  arr2 = arr[0:3] #arr2 and put it in a new object named arr here we copied the first three elements in the object
	  
		  print(arr2) # arr2 Here we have shown what the object contains
	

We will get the following result when running.

(10, 20, 30)

Using the factors +and *and inwiththetuplein python


The Worker Indications
+ An operator +is used to combine one tupleor more into tupleone.
* Operator *for setting to repeat a given value multiple times inThe tuple.
in The operator inis used to search inthetupleAbout a specific value or to pass its values ​​when using it in the loop, foras we did in some of the previous examples.

In the following example we store two tuplein tupleone by the operator +.

first example

Test.py
arr1 = (1, 2, 3) # We put integers in it arr1 named tuple here we define
		  arr2 = (4, 5, 6) # we put integers in it arr2 named tuple here we have defined
	  
		  arr3 = arr1 + arr2 # arr2 and arr1 we put the values ​​of the two objects arr3 named tuple here we have defined
	  
		  print(arr3) # arr3 Here we have shown what the object contains
	

We will get the following result when running.

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


In the following example we have defined tupleand put 3 elements that have 'python'as their value by the operator *.

second example

Test.py
arr = ('python',) * 3 # 'python' we put in it 3 elements whose value is the text arr named tuple here we have defined
	  
		  print(arr) # arr Here we have shown what the object contains
	

We will get the following result when running.

('python', 'python', 'python')

Whatch out

When repeating values ​​inthetupleWith the operator *, you are forced to put a comma after the value you put in the parentheses.
If you don't put a comma after the value, the Python compiler won't know that you intended to definetuple.



In the following example, we used the operator into search inthetupleabout a certain value.

third example

Test.py
arr = ('Mhamad', 'Rony', 'Rima', 'Sara') # we put a set of text values ​​in it arr named tuple here we have defined
	  
		  x = 'Rima' # We put the text x here we have defined a variable named
	  
		  print('Is Rima in the tuple?')
		  print(x in arr) # True if found then .arr will be shown in object x here the value will be searched for
	

We will get the following result when running.

Is Rima in the tuple?
True

 Class functions tuplein Python

Function name and definition
count(x) used to search inthetuplewho called it for a certain value.
Returns an integer representing how many times an element has been found that has the same value as the parameter we passed x.
see example »
index(x[, start[, end]]) search inthetuplewho summoned herIndexThe first element that has the value we pass to it is in place of the parameter xand returns it.
If the value you want to know is not found, an exception is thrownValueError .
see example »

Ready functions in Python to handlethetuple

Function name and definition
len(tuple) Returns an integer representing the number of elementsthetuplewhich we pass to her when she is summoned.
see example »
min(tuple) Returns the smallest value in .thetuplewhich we pass to her when she is summoned.
see example »
max(tuple) Returns the largest value inthetuplewhich we pass to her when she is summoned.
see example »
tuple(sequence) Returns a copy of any object containing a set of elements that we pass to it when called as a class objectThe tuple.
see example »

 Utility of type tuplein Python

Since you found the type to tuplebe a bit more limited compared to the type listyou studied in the previous lesson, you may be wondering about its usefulness.

These reasons are what may push you to type tuple:

  • Reaching items placed in tuplefaster than accessing items placed inlist.

  • Its value is considered safe as it can only be read.

  • In the event that you are using the type dictionaryin which the data is placed as a table consisting of keys(Keys)and rate(Values).It can pass tuplecontaining numbers or texts as its keys.

 Python tuple -  functioncount()

its definition

used to search inthetuplewho called it for a certain value.
Returns an integer representing how many times an element has been found that has the same value as the parameter we passed x.



built

                  table.count(x)
	  


parameters

position of the parameterx we pass the object or value we want to find inThe tuple.



Return value

Returns an integer representing how many times an element has been found inthetupleThe one who called it has the same value that we passed to it in place of the parameter x.


Example

Test.py
                    # We put in it a set of integers called a tuple, here we have defined
		  atuple = (1, 3, 8, 4, 3, 3, 7, 2, 3, 4, 3)
	  
		  # found and then we put the result in the variable atuple to return how many times the value '3' is found in the object count() here we called the function
		  found = atuple.count(3);
	  
		  # found Here we have shown the value in the variable
		  print('Number 3 exists', found, 'in the tuple')
	

We will get the following result when running.

Number 3 exists 5 in the tuple

 Python tuple -  functionindex()

its definition

search inthetuplewho summoned herIndexThe first element that has the value we pass to it is in place of the parameter xand returns it.
If the value to be searched is not found, an exception is thrownValueError .


built

                  index(x[, start[, end]])
	  


parameters

  • xAn expression for the value or object we want to find.

  • startOptional parameter, you can pass in place an integer specifying a numbertheIndexWhere do you want to start your search?

  • endOptional parameter, you can pass in place an integer specifying a numbertheIndexWhich you want to stop searching before.



Return value

return numberIndexThe first element that has the value we pass to it is in place of the parameter x.



Possible errors

Throws a ValueError if the value you want to know is not found.



Example

Test.py
                    # We put in it a set of integers called a tuple, here we have defined
		  atuple = (1, 2, 3, 4, 5)
	  
		  #3 The first element that has the value index here we have shown
		  print(atuple.index(3))
	  
		  # atuple is the first element that has the value 3 and we start the search process from the second element in the index object here we have shown
		  print(atuple.index(3, 1))
	  
		  # And up to the last element in which the atuple is, the first element has the value 3 and we start the search process from the second element in the index object here we have shown
		  print(atuple.index(3, 1, 5))
	  
		  # When running ValueError the first element that has the value 10. Since there is no element that has this value, the index error will appear here. We have shown
		  print(atuple.index(10))
	

We will get the following result when running.

2
2
2
ValueError: 10 is not in tuple

 Python tuple -  functionlen()

its definition

Returns an integer representing the number of elementsthetuplewhich we pass to her when she is summoned.



built

                  len(tuple)
	  


parameters

The location of the parameter tuplewe passthetuplefor which we want to get the number of its elements.



Return value

Returns an integer representing the number of elementsthetuplewhich we pass to her when she is summoned.


Example

Test.py
                    # We put in it a set of integers called a tuple, here we have defined
		  atuple = (1, 2, 3, 4, 5)
	  
		  # len() that the atuple function will return here we have shown the number of elements of the object
		  print('Tuple length is:', len(atuple))
	

We will get the following result when running.

Tuple length is: 5

 Python tuple -  functionmin()

its definition

Returns the smallest value inthetuplewhich we pass to her when she is summoned.



built

                  min(tuple)
	  


parameters

The location of the parameter tuplewe passthetuplein which we want to get the smallest value.



Return value

Returns the smallest value inthetuplewhich we pass to her when she is summoned.


Example

Test.py
                    # We put in it a set of integers called a tuple, here we have defined
		  atuple = (5, 2, 4, 6, 3)
	  
		  # min() which the atuple function will return here we have shown the smallest value in the object
		  print('Minimum value is:', min(atuple))
	

We will get the following result when running.

Minimum value is: 2

 Python tuple -  functionmax()

its definition

Returns the largest value inthetuplewhich we pass to her when she is summoned.



built

                  max(tuple)
	  


parameters

The location of the parameter tuplewe passthetupleWhich we want to get the most value in.



Return value

Returns the largest value inthetuplewhich we pass to her when she is summoned.


Example

Test.py
                    # We put in it a set of integers called a tuple, here we have defined
		  atuple = (5, 2, 4, 6, 3)
	  
		  # max() which the atuple function will return here we have shown the largest value in the object
		  print('Maximum value is:', max(atuple))
	

We will get the following result when running.

Maximum value is: 6

 Functiontuple()

its definition

Returns a copy of any object containing a set of elements that we pass to it when called as a class objectThe tuple.



built

                  tuple(sequence)
	  


parameters

In place of the parameter sequence, we pass an object that represents an object that represents an array of elements.



Return value

Returns a copy of any object containing a set of elements that we pass to it when called as a class objectThe tuple.


first example

Test.py
                    # We put in it a set of integers called aSet. Here we have defined
		  aSet = {1, 2, 3, 4, 5}
	  
		  # atuple that you will return in the tuple then we have stored the .tuple to return a copy as an aSet on the tuple() here we called the function
		  atuple = tuple(aSet)
	  
		  # atuple Here we have shown what the object contains
		  print(atuple)
	

We will get the following result when running.

(1, 2, 3, 4, 5)