Example 1: what is a tuple in python
# A tuple is a sequence of immutable Python objects. Tuples are
# sequences, just like lists. The differences between tuples
# and lists are, the tuples cannot be changed unlike lists and
# tuples use parentheses, whereas lists use square brackets.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = "a", "b", "c", "d";
# To access values in tuple, use the square brackets for
# slicing along with the index or indices to obtain value
# available at that index.
tup1[0] # Output: 'physics'
Example 2: how to print a tuple in python
tuple1 = ("car", "bike", "bus")
print(tuple1)
Example 3: tuples in python
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
Example 4: what are tuples
Tuples in Python
An immutable data value that contains related elements.
Tuples are used to group together related data,
such as a person’s name, their age, and their gender.
A tuple is the same as a list except uses parenthisies instead of square brackets.
A tuple is also immutable (cant be changed) unlike a list.
Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
Example 5: tuples
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Example 6: tuple() python
example = [1, 2, 3, 4]
# Here is a list above! As we both know, lists can change in value
# unlike toples, which are not using [] but () instead and cannot
# change in value, because their values are static.
# list() converts your tuple into a list.
tupleexample = ('a', 'b', 'c')
print(list(tupleexample))
>> ['a', 'b', 'c']
# tuple() does the same thing, but converts your list into a tuple instead.
print(example)
>> [1, 2, 3, 4]
print(tuple(example))
>> (1, 2, 3, 4)