list
. But unlike list
they are Immutable (items cannot be altered/deleted), so they are preferred when data should not be changed. They are data efficient than list
and are slightly faster than list
. Indexing, Slicing is supported and they are iterable objects just like lists, but there is no tuple
comprehension (it becomes a generator).list
which are mostly used for storing similar items, but either way is also valid.tuple
.# Create a empty tuple
some_tuple = ()
# or using tuple() function
some_tuple = tuple()
# Initialize with items, insert items inside '()' brackets
my_tuple = (1, 2, 3, "we", "are", "one", 5.0)
tuple
.## Tuple is immutable, there is no 'append/remove', can't use 'del' like in list
# so to add a element join two tuples and assign it to a previous/new variable
my_tuple = (1, 2, 3, 4)
# adding another element as tuple, it's basically joining two tuples
my_tuple += (5,)
print(my_tuple) # (1, 2, 3, 4, 5)
# Notice: The target tuple should have ',' if single element is being added
# else will give the type of variable inside parenthesis and not tuple,
# for example
some_tuple = (5)
print(type(some_tuple)) # <class 'int'>
tuple
.## Joining: Join two or more tuples
my_tuple1 = (34, 65, 23) + (34, 34)
print(my_tuple1) # (34, 65, 23, 34, 34)
## Multiplying: Multiply using '*' operator on a tuple
my_tuple1 = (34, 65, 23) * 2
print(my_tuple1) # (34, 65, 23, 34, 65, 23)
tuple
.my_tuple = (1, 2, 3, "we", "are", "one", 5.0)
## Indexing: Accessing item/character from tuple
my_var = my_tuple[0]
# Raises 'TypeError', because Immutable type
my_tuple[0] = 23
# Note: Make sure to comment above line to execute the program further
## Iterating: Going over item by item from a tuple
for var in my_tuple:
print(var) # (1,2,3,'we','are','one',5.0)
# checking if some value is present using the 'in' operator
if 5.0 in my_tuple:
print("printed") # printed
## Slicing: For creating sub-tuple, syntax [start_index:end_index:step]
print(my_tuple[3:5]) # ('we','are')
print(my_tuple[5:]) # ('one',5.0)
print(my_tuple[:3]) # (1,2,3)
print(my_tuple[:5:2]) # (1,3,'are')
# negative indexing
print(my_tuple[:-4]) # (1,2,3)
print(my_tuple[:-2:2]) # (1, 3, 'are')
# reverse a tuple
print(my_tuple[::-1]) # (5.0, 'one', 'are', 'we', 3, 2, 1)
tuple
.## Unpacking tuple (more on unpacking later on)
# Unpacking values into a,b,c
a, b, c = (1, 2, 3)
# even below line does the same, 1,2,3 becomes a tuple
# and then unpacks into a,b & c, same is true when returning
# comma separated values from a function
a, b, c = 1, 2, 3
# this behaviour further aids in swapping without using extra variable,
# you can also do the same with more variables
a, b = b, a
tuple
.my_tuple1 = (3, 2, 6, 2, 5, 3, 1, 1)
# Returns the number of occurrences of value
print(my_tuple1.count(3)) # 2
# Returns the first index of value
print(my_tuple1.index(2)) # 1
tuple
.my_tuple = (3, 6, 1, 8, 2, 3)
# Returns a sorted list of items in ascending order by default
# can be reversed using the 'reverse' parameter
print(sorted(my_tuple, reverse=True)) # [8, 6, 3, 3, 2, 1]
# Returns the length of tuple
print(len(my_tuple)) # 6
my_tuple = tuple([1, 2, 3, 4, 5]) # list to tuple
my_tuple = tuple({1, 2, 3, 4, 5}) # set to tuple
Time Complexity
tuple
i.e regular tuples that support field/item names. So along with indexing they support accessing fields/elements using their names with the '.' operator (just as accessing the class attributes).tuple
. When instantiated they return a new tuple
subclass named <typename>. This new subclass can be used to create tuple-like objects which are also immutables, indexable, iterables and are as data efficient as a regular tuple
.collections
module. They provide more readable, self-documenting code over the regular tuple
where they are intended.namedtuple
saves you most of the hassle of writing the code for operations (like iterable, indexing) with the convenience of naming access.namedtuple
.from collections import namedtuple
import sys
# first parameter of namedtuple is typename: string which is
# the name of a tuple subclass
# second parameter is field_names: iterable/string
# which has names of fields/variables/data tuple will contain
Name_tup = namedtuple("mynamedtuple", ["a", "b"])
# or provide names from a single string (separated by space)
Name_tup = namedtuple("mynamedtuple", "a b")
# print the class name
print(Name_tup) # <class '__main__.mynamedtuple'>
## Create the namedtuple object
name_tup1 = Name_tup(42, 65)
# can also create another object with different data type
name_tup2 = Name_tup("oh", "this")
print(name_tup1) # mynamedtuple(a=42, b=65)
print(name_tup2) # mynamedtuple(a='oh', b='this')
## Accessing elements with names
print(name_tup2.a) # oh
print(name_tup2.b) # this
## Comparing with regular tuple
print(name_tup1 == (42, 65)) # True
# comparing their sizes
print(sys.getsizeof(name_tup1), sys.getsizeof((42, 65))) # 56, 56
# like regular tuple immutable
name_tup1[0] = 32 # TypeError
namedtuple
.from collections import namedtuple
Name_tup = namedtuple("mynamedtuple", ["aa", "bbk", "cab"])
name_tup1 = Name_tup(42, 60, 52)
## Indexing like tuples
print(name_tup1[0]) # 42
print(name_tup1[1]) # 60
## Iterating
for a in name_tup1:
print(a) # 42,60,52
## Slicing
print(name_tup1[1:]) # (60, 52)
namedtuple
.from collections import namedtuple
Name_tup = namedtuple("mynamedtuple", ["aa", "bbk", "cab"])
name_tup1 = Name_tup(42, 60, 52)
# Convert to dictionary
print(name_tup1._asdict()) # {'aa': 42, 'bbk': 60, 'cab': 52}
# Replace the value, creates and returns a new mynamedtuple instance
print(name_tup1._replace(aa=32)) # mynamedtuple(aa=32, bbk=60, cab=52)