456
How to determine the length of a Python tuple?
In Python, we can use the len() function to determine the length of a Python tuple or how many items are stored in the tuple. For example,
numbers = (1, 5, 23, 67, 2, 456, 87, 5) print(len(numbers))
There are 8 numbers stored in the tuple. The program will print the following output:
8
How to create a new tuple from existing Python tuples?
As I said, tuples are immutable in Python. So, once we store some items in a tuple, we cannot change them later. But, we can take existing tuples and create a new tuple from them. For example,
t1 = (1, 2, 3) t2 = (4, 5, 6) t3 = t1 + t2 print(t3)
Here, the tuple t1 contains the numbers 1, 2, 3 and the tuple t2 contains the numbers 4, 5, 6. We are creating a tuple t3 from t1 and t2. The tuple t3 will contain the numbers 1, 2, 3, 4, 5, and 6. The above program will print the following output:
(1, 2, 3, 4, 5, 6)
Now, let’s say we want to take the first two items from t1 and the last number from t2 and create the tuple t3. In other words, we want the tuple t3 to contain the numbers 1 and 2 from t1 and 6 from t2. We can do so easily using the following program:
t1 = (1, 2, 3) t2 = (4, 5, 6) t3 = t1[:2] + t2[2:] print(t3)
Here, t1[:2] will contain the numbers 1 and 2 from index 0 and index 1 of the tuple t1. And, t2[2:] will contain the numbers from index 2 of the tuple t2. So, t3 will contain the numbers 1, 2, and 6. The above program will print the following output:








































0 Comments