Python Basics: Immutable Sequence Type & Tuples 2

To get an element of a tuple in order to read them over, you can use the same way while you are using a list:

tuple=(1, 10, 100, 1000)
 print(tuple[0]) -> the index is 0, so output is 1
 print(tuple[-1]) -> the last index, so the output is 1000
 print(tuple[1:]) -> starting index is 1, so the output is (10,100,1000)
 print(tuple[:2]) -> ending index is 2, so the output is (1,10)
 print(tuple[2:3]) -> output is 100
 for i in tuple:
    print(i) -> print the elements (i) in tuple

As mentioned in previous post, tuple is an immutable sequence type which means its content cannot be modified like a list.

The “+” sign can concatenate two tuples giving a new tuple containing all the elements from those two tuples:

tuple1 = (1,2,3,4)
 tuple2 = (0,2,9)
 print(tuple1 + tuple2) -> The output is (1,2,3,4,0,2,9)

The * operator can multiply tuples:

tuple1 = (1,2,3,4)
 tuple2 = (0,2,9)
 print(tuple1 * 2) -> The output is (1,2,3,4,1,2,3,4)
 *tuple cannot multiply tuple

You can also use in or not in keywords with tuples.

In addition, a tuple’s elements can be variables, not only literal data (values that define themselves); and the elements can be expressions if they are on the right side of the assignment (equal sign) operator:

v1 = 1
 v2 = 2
 v3 = 3
 v1, v2, v3 = v2, v3, v1 <- two tuples interacting
 #In python, if you want to swap values of variales, you can do something above

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.