Python | Initialize tuples with parameters
This article deals with initializing the tuples with parameters. Namely, default value, size, and specific value at 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 combination of above functionalities. In this, we extend the default values using * operator and perform the formation of tuple using tuple()
# Python3 code to demonstrate working of # Initialize tuples with parameters # Using tuple() + * operator # Initializing size N = 6 # Initializing default value def_val = 2 # Initializing index to add value idx = 3 # Initializing value to be added val = 9 # Initialize tuples with parameters # Using tuple() + * operator res = [def_val] * N res[idx] = val res = tuple(res) # printing result print("The formulated tuple is : " + str(res)) |
The formulated tuple is : (2, 2, 2, 9, 2, 2)
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 specific element is initialized at specific position using comparison.
# Python3 code to demonstrate working of # Initialize tuples with parameters # Using tuple() + generator expression # Initializing size N = 6 # Initializing default value def_val = 2 # Initializing index to add value idx = 3 # Initializing value to be added val = 9 # Initialize tuples with parameters # Using tuple() + generator expression res = tuple(val if i == idx else def_val for i in range(N)) # printing result print("The formulated tuple is : " + str(res)) |
The formulated tuple is : (2, 2, 2, 9, 2, 2)
Recommended Posts:
- Python | Remove duplicate tuples from list of tuples
- Python | Find the tuples containing the given element from a list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Convert string tuples to list tuples
- Python | Count tuples occurrence in list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Combining tuples in list of tuples
- Python | How to Concatenate tuples to nested tuples
- Initialize Matrix in Python
- Decorators with parameters in Python
- Python | Initialize dictionary with common value
- Python | Which is faster to initialize lists?
- Python | Initialize common value to keys
- Python | Initialize dictionary with None values
- Python | Ways to initialize list with alphabets
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



