Q:

Python | Rear elements from Tuple Strings

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Extracting rear elements from tuple String

In this program, we have a tuple with string elements. And we need to create a python program to extract all elements from the tuple of string elements.

Input:
("python", "learn", "includehelp")

Output:
["n", "n", "p"]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One simple way to solve the problem is by traversing the tuple and then for each string element extract the (n-1)th index value. This is done in a string line of code using list comprehension.

# Python Program to extract rear elements 
# from the tuple string 

# Creating and printing tuple string 
myTuple = ("python", "learn", "includehelp")
print("The elements of the tuple string are : " + str(myTuple))

# Extracting the last element from each 
# string element of the tuple
rearEleList = list(val[len(val) - 1] for val in myTuple)

# Printing the element list
print("The rear elements of each string from the tuple : " + str(rearEleList))

Output:

The elements of the tuple string are : ('python', 'learn', 'includehelp')
The rear elements of each string from the tuple : ['n', 'n', 'p']

Method 2:

Another method to perform the task is by directly using a loop to iterate over each element of the tuple. For each string of the tuple, extract the rear element i.e. element at (n-1)th index.

# Python program to extract rear elements 
# from the tuple string 

# Creating and printing tuple string 
myTuple = ("python", "learn", "includehelp")
print("The elements of the tuple string are : " + str(myTuple))

# Extracting the last element from the 
# each string element of the tuple
rearEleList = []
for strVal in myTuple :
    N = len(strVal) - 1 
    rearEleList.append(strVal[N])

# Printing the element list
print("The rear elements of each string from the tuple : " + str(rearEleList))

Output:

The elements of the tuple string are : ('python', 'learn', 'includehelp')
The rear elements of each string from the tuple : ['n', 'n', 'p']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Index Maximum among Tuples... >>
<< Python | Union of Tuples...