
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a Non-Literal Python Tuple
A tuple in Python is an ordered, immutable collection that stores multiple items. It supports mixed data types, allows indexing, and is commonly used for fixed data structures.
Non-literal Tuple
Literal Tuple
Non-Literal Tuple
A non-literal tuple in Python is created dynamically using code instead of being written directly with parentheses and values like (2, 4, 6).
# From a list data = [2, 4, 6] t = tuple(data) print(t) # From a generator t = tuple(i for i in range(3)) # (2, 4, 2) print(t) # From unpacking a, b = 2, 4 t = (a, b) print(t)
The result is generated as follows ?
(2, 4, 6) (0, 1, 2) (2, 4)
Literal Tuple
A literal tuple in Python is directly defined using parentheses and values, like(1, 2, 3). This is a fixed, immutable sequence written exactly as is in the code.
a = (2, 4, 6) print(a)
We will get the output as follows ?
(2, 4, 6)
What is a Non-Literal Tuple in Python?
A non-literal tuple in Python is dynamically created using expressions or functions instead of defining values within parentheses, like (1, 2, 3). It is formed through code instead of direct declaration.
We can start by constructing a list, then modify the specific value we need to change, and finally convert it into a tuple if we need to create a non-literal Python tuple. For example -
def create_non_literal_tuple(a, b, c): x = [1] * a x[c] = b return tuple(x) create_non_literal_tuple(6, 0, 2)
This will give the output:
(1, 1, 0, 1, 1, 1)
A 0 in position 2 of an array of length 6.
Creating a Non-Literal Tuple
Tuples are immutable sequences in Python. This code initializes a list of data with values [20, 30, 40], converts it into a tuple using tuple(data), and prints the result.
data = [20, 30, 40] my_tuple = tuple(data) print(my_tuple)
The result is generated as follows ?
(20, 30, 40)