Python Tuples and Tricks By albro

in Programming & Dev3 years ago

Python Tuples and Tricks

A tuple in Python is an ordered and immutable set of values. With the help of tuples, we can store several values of different data types in a variable and perform operations on them. In this post, I will talk about the tuple data structure in Python and its tricks.

Tuple is a type of collection that can store an unlimited number of values.

In terms of definition and usage, it's similar to list in Python. Of course, they have clear differences that we will get to know later. If you're not familiar with lists, I suggest that you definitely learn to work with lists because they are very useful.

Unlike lists, values defined as tuples are immutable. That is, when we create a tuple with three values, we cannot change their value and number.

Definition of tuple in Python

To define a tuple in Python, open and close parentheses are generally used at the beginning and end. We separate the desired values with a comma (,).

Below I have created a tuple with five values.

my_tuple = (217, "albro", 23.471, 9, "Hive")

As you can see, each tuple element can be of a different data type. In this example, I used numbers and strings in Python; But we can also use a list object or another tuple!

Tuple members are not necessarily different! For example, below we put three numbers in a tuple.

tpl = (17, 14, 20)

If we put an open and close parentheses for a variable, we have created an empty tuple.

empty_tuple = ()

Be careful that if our tuple contains only one element, we must also put a comma after the element definition.

test = (27,)

If we don't put the sign , after the single member in the tuple, that variable is no longer a tuple and its type will be of the same type as the member element.

In the image below, I have put the name of the hive as a string in parentheses and assigned it to the test variable. When I check the variable type, we see that string is recognized.

Define single element without comma in tuple

Access to tuple elements

Similar to the list or string that has an index to access its elements, we use indexes to access tuple elements in Python.

To access the nth element, it is enough to write the name of the tuple and write the index number of the desired house in the brackets ([]).

The first member of a tuple has index number zero (0) and its last member (nth) has index n-1.

Suppose we have the following tuple.

tpl = ("albro", "ecency", "xeldal", "ocdb", "mightpossibly", "leo.voter")

To access the third member of this tuple, we must call index 2 or -4; As follows:

print( tpl[2] )
print( tpl[-4] )

Range access to elements

Similar to other collection type data, slicing operations can be performed on tuples. For this, it is enough to define the range of indices with the sign : during the call.

tpl = ("albro", "ecency", "xeldal", "ocdb", "mightpossibly", "leo.voter")
print( tpl[1:5] )
# Result:
# ('ecency', 'xeldal', 'ocdb', 'mightpossibly')

In the code below, you'll see more examples of accessing tuple members in these same ways.

print( tpl[2:-1] )
# ('xeldal', 'ocdb', 'mightpossibly')
print( tpl[-5:-1] )
# ('ecency', 'xeldal', 'ocdb', 'mightpossibly')
print( tpl[-4:4] )
# ('xeldal', 'ocdb')

Tuple editing in Python

Tuples are immutable. Therefore, we will not be able to change the members of a tuple like lists!

In the image below, I have defined a tuple and I want to change the value of its second house. As you can see, I got a TypeError.

Error changing tuple element value in Python

The most fundamental difference between a list and a tuple in Python is that because tuple is immutable in Python, we cannot change its values or increase or decrease their number.

but don't worry! In the following, we will learn the method by which we will be able to have a new tuple with new members using the current values.

Add new member to tuple

The addition operator (+) is used to join two tuples together. When using this operator, the first and second tuple values are put together and a new tuple is created.

Note that the previous tuples are neither deleted nor changed, only a new tuple will be created with their members.

Suppose we have tuple1 and tuple2. In the following code, we combine these two tuples with the addition operator and create tuple3.

tuple1 = ( "Test", "Element" )
tuple2 = ( 11, 37, 23 )
tuple3 = tuple1 + tuple2

The result of concatenating two tuples is as follows.

print( tuple3 )
# ('Test', 'Element', 11, 37, 23)

Remove tuple elements

Just as it is not possible to change an element in a tuple, it is also not possible to delete an element. We can only delete the entire tuple.

To delete a tuple in Python, we use the del keyword before its name. This will remove all members of the tuple and the tuple itself.

tpl = ("albro", "xeldal", "mightpossibly")
# Some Codes...
del tpl

Note that if I call it after removing the tuple, I get an error similar to the one below. Because there is no such variable in the program.

Checking tuple deletion in Python with the del statement

tricks

With the help of operators and key expressions, we can work with tuples more professionally. In the following, I'll discuss four of them.

Tuple size with len function

The len() function takes a tuple as input and returns the number of elements in it.

tpl = ("xeldal", "ocdb", "leo.voter", "steemstem")
len( tpl ) # 4

Concating tuples to each other

We concatenate two tuples to add a new element to the tuple. This work is called concat.

For this purpose, between two or more desired tuples, we use the plus sign (+).

By doing this, the tuples are concatenated and a larger tuple containing their members is created.

tuple1 = ( "Test", "Element" )
tuple2 = ( 11, 37, 23 )
tuple3 = tuple1[1:] + tuple2[:-1]
print( tuple3 )
# Result:
# ('Element', 11, 37)

Iterate tuple elements in Python

Suppose you have a tuple with two elements. You want to iterate over these elements and put them in a new tuple.

For this, we use the mathematical multiplication sign (*). It is enough to multiply the tuple by the desired number of repetitions. With this, we will have a new tuple with arbitrary repetition of the previous elements.

tpl = ("xeldal", "mightpossibly")
print( tpl*3 )
# Result:
# ('xeldal', 'mightpossibly', 'xeldal', 'mightpossibly', 'xeldal', 'mightpossibly')

Checking the existence of an element in a tuple

If we want to check the existence of a value in the tuple, we will use the in keyword. We put the desired value on the left side and our tuple on the right side.The output of this expression will be True or False; So it can be used in Python's conditional structures as well.

tpl = (17, 25, 32, 37, 42, 50)
print( 32 in tpl ) #True
print( 35 in tpl ) #False

Summary

In this post, we learned about tuples in Python. We specify the tuple with parentheses. Its elements and length are immutable, and if we want to add a new member to it, we technically need to create a new tuple.

Sort:  

https://leofinance.io/threads/view/albro/re-leothreads-54rux6sa
The rewards earned on this comment will go directly to the people ( albro ) sharing the post on LeoThreads,LikeTu,dBuzz.

Congratulations @albro! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 4750 upvotes.
Your next target is to reach 5000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Our Hive Power Delegations to the April PUM Winners
Feedback from the May Hive Power Up Day
The Hive Gamification Proposal
Support the HiveBuzz project. Vote for our proposal!

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

Congratulations!


You have obtained a vote from CHESS BROTHERS PROJECT

✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪


♟ We invite you to use our hashtag #chessbrothers and learn more about us.

♟♟ You can also reach us on our Discord server and promote your posts there.

♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.

♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.


🥇 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.


Kindly

The CHESS BROTHERS team