Initialize tuples with parameters in Python


When it is required to initialize the tuples with certain parameters, the 'tuple' method and the '*' operator can be used.

The 'tuple' method will convert the iterable passed to it as parameter into a tuple class type.

The * operator can be used to get the product of two values. It can also be used to multiple a single value multiple times and display it on the console.

Below is a demonstration for the same −

Example

Live Demo

N = 6
print("The value of N has been initialized to "+str(N))

default_val = 2
print("The default value has been initialized to " +str(default_val))

indx = 3
print("The index value has been initialized to "+ str(indx))

val_to_add = 6
print("The value to be added is initialized to " +str(val_to_add))

my_result = [default_val] * N
my_result[indx] = val_to_add
my_result = tuple(my_result)

print("The tuple formed is : ")
print(my_result)

Output

The value of N has been initialized to 6
The default value has been initialized to 2
The index value has been initialized to 3
The value to be added is initialized to 6
The tuple formed is :
(2, 2, 2, 6, 2, 2)

Explanation

  • The value for 'N', 'index', 'value to be added' and a default value are initialized and displayed on the console.
  • The default value is multiplied with 'N' and assigned to a variable.
  • This operation is assigned to a variable.
  • That variable's 'index' is assigned the value that needs to be added.
  • Next, the variable is converted into a tuple, and stored in a variable.
  • This variable is the output that is displayed on the console.

Updated on: 12-Mar-2021

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements