This article deals with initializing the tuples with parameters. Namely, default value, size, and specific value at a specific index. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple() + * operator This task can be performed using a combination of the above functionalities. In this, we extend the default values using the * operator and perform the formation of a tuple using tuple()
Python3
N = 6
def_val = 2
idx = 3
val = 9
res = [def_val] * N
res[idx] = val
res = tuple (res)
print ("The formulated tuple is : " + str (res))
|
Output :
The formulated tuple is : (2, 2, 2, 9, 2, 2)
Time Complexity: O(N), where N is the size of the tuple to be initialized.
Auxiliary Space: O(N)
Method #2: Using generator expression + tuple() This task can be performed using generator expression along with tuple() as well. The elements are created one by one on this and a specific element is initialized at a specific position using comparison.
Python3
N = 6
def_val = 2
idx = 3
val = 9
res = tuple (val if i = = idx else def_val for i in range (N))
print ("The formulated tuple is : " + str (res))
|
Output :
The formulated tuple is : (2, 2, 2, 9, 2, 2)
Approach#2: Using the list: The approach used in the given code is to first create a list of size N with all elements initialized to the default value def_val using list comprehension. Then, the value val is inserted at index idx in the list. Finally, the list is converted to a tuple using the tuple() function.
- Initialize the size N, default value def_val, index idx and value to be added val.
- Create a list of size N with all elements initialized to def_val using list comprehension.
- Replace the element at index idx in the list with val.
- Convert the list to a tuple using the tuple() function.
- Print the tuple.
Python3
N = 6
def_val = 2
idx = 3
val = 9
tup = tuple ([def_val] * N)
lst = list (tup)
lst[idx] = val
tup = tuple (lst)
print ( "The formulated tuple is:" , tup)
|
Output
The formulated tuple is: (2, 2, 2, 9, 2, 2)
Time Complexity: O(N) because the list comprehension takes O(N) time to create a list of size N with all elements initialized to def_val.
Space Complexity: O(N) because a list of size N is created to store the elements before converting it to a tuple. The tuple itself takes O(N) space as well.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 May, 2023
Like Article
Save Article