How to Get First & Last Elements From a Tuple in Python | EP-14 Get First & Last Elements from Tuple
1. Get First and Last Elements from a Tuple Using Indexing
"""We can use indexing to access the first and last elements of the tuple.
Python indexing starts at 0 for the first element and -1 for last element."""
my_tuple = (10,20,30,40,50)
first_element = my_tuple[0]
last_element = my_tuple[-1]
print(" first element:",first_element)
print("last element:",last_element)
method 2:
my_tuple = tuple(map(int,input("enter the elements").split()))
print(my_tuple)
first = my_tuple[0]
last = my_tuple[-1]
print("first_element",first)
print("last_element",last)
2. Get First and Last Elements from a Tuple Using Tuple Unpacking
"""using *_ clearly indicates that you intend to capture and discard
(in the case of unpacking) or store a collection of remaining arguments."""
my_tuple3 = (1,2,3,4)
first_element,*_,last_element = my_tuple3
print("first_element",first_element)
print("last_element",last_element)
3. Get First and Last Elements from a Tuple Using Slicing
my_tuple4 =("a","b","c")
first =my_tuple4[:1][0]
last =my_tuple4[-1]
print("first_element",first)
print("last_element",last)
#PythonTutorials #PythonBasics #PythonProgramming #PythonTips #LearnPython #PythonForBeginners #Coding #Programming #TuplesInPython #python #pythonbeginner #pythontips #tuple #tuplemanipulation #getfirstelement #getlastelement #coding #programming #tutorial
Connect With Us:
—————————————
➡️ Website: https://www.cybrosys.com/
➡️ Email: info@cybrosys.com
➡️ Twitter: / cybrosys
➡️ LinkedIn: / cybrosys
➡️ Facebook: / cybrosystechnologies
➡️ Instagram: / cybrosystech
➡️ Pinterest: / cybrosys