Q:

Python program for creating N element incremental tuple

belongs to collection: Python Tuple Programs

0

Example:

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

N element incremental Tuples

In this program, we are given a number N and a range (L, R). We need to create Python program for creating N element incremental tuple. We will create a tuple for each element of the range, with i [in the range (L, R)] repeatedly N times.

Input:
N = 4, [L, R] = [3, 6]

Output:
((3, 3, 3, 3), (4, 4, 4, 4), (5, 5, 5, 5), (6, 6, 6, 6), )

For this, we will loop for the range and for each number of range create repeat the given number N time and create a tuple with these elements.

All Answers

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

Method 1:

One method to create N incremental tuples is by using a generator expression in which we will iterate through all elements in the range [L, R] and create a tuple with N element of that range. And finally, encapsulate it in a tuple using the tuple() method.

# Python program for creating 
# N element incremental tuple

# Initializing and printing N and range
N = 4
L = 2
R = 7

print("The Value of N is " + str(N))
print("The range is (" + str(L) + ", " + str(R) + ")")

# creting N element incremental tuples
incrTuple = tuple((value, ) * N for value in range(L, R))

print("Tuple consisting of N element incremental Tuple is " + str(incrTuple))

Output:

The Value of N is 4
The range is (2, 7)
Tuple consisting of N element incremental Tuple is ((2, 2, 2, 2), (3, 3, 3, 3), (4, 4, 4, 4), (5, 5, 5, 5), (6, 6, 6, 6))

Method 2:

Another method to solve the problem is by using the repeat method to repeat the value of range N times. And create a tuple using the generator expression only.

# Python program for creating 
# N element incremental tuple

import itertools

# Initializing and printing N and range
N = 4
L = 2
R = 7

print("The Value of N is " + str(N))
print("The range is (" + str(L) + ", " + str(R) + ")")

# creting N element incremental tuples
incrTuple = tuple(tuple(itertools.repeat(ele, N)) for ele in range(L, R))

print("Tuple consisting of N element incremental Tuple is " + str(incrTuple))

Output:

The Value of N is 4
The range is (2, 7)
Tuple consisting of N element incremental Tuple is ((2, 2, 2, 2), (3, 3, 3, 3), (4, 4, 4, 4), (5, 5, 5, 5), (6, 6, 6, 6))

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 program to perform XOR operation on tuples... >>
<< Python program to create a tuple from string and l...