Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 24332

IslandT: Python Tutorial — Chapter 7

$
0
0

In this chapter let us look at how to store various items within a tuple. A tuple is just like a list that can be used to store multiple items and then allows us to retrieve those items through its index.

Here is how to declare a tuple, either through its constructor or the (), and how to retrieve a particular item within that tuple.

atuple = tuple((1,2,3))
atuple1 = (1,2,3)
atuple[0] # 1, the index of a tuple started at index 0

In the below example let us create the above tuple again and use the for loop, to sum up, all those numbers within that tuple.

atuple = tuple((1,2,3))
    sum = 0
    for num in atuple:
        sum += num
    print(sum) # 6

Just like a list, those elements within the tuple consists of various types:

atuple = ("hi", True, 1)

Tuple is one of the Array data type used in Python and its function is basically almost the same as a list!


Viewing all articles
Browse latest Browse all 24332

Trending Articles