define tuple python code example

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: pyhton tuple

#It's like a list, but unchangeable
tup = ("var1","var2","var3")
tup = (1,2,3)
#Error

Example 3: py tuple

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple) # ()

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple) # (1, 2, 3)

# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple) # (1, 'Hello', 3.4)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple) # ('mouse', [8, 4, 6], (1, 2, 3))

Example 4: 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)

Example 5: tuples in python

# the tuples are like the Read-Only they are not to be changed or modified they're constant

letters = "a", "b", "c", "d"    # you can use () as they are optional
print(letters)
"""
    tuples are immutable but it's important because they don't returns the bugs
    
    these are sequence types means you can iterate over them by it's index numbers
    
    tuples data can't be changed but list's data can be changed
"""

Tags:

C Example