Skip to content

Instantly share code, notes, and snippets.

@Clivern
Created March 21, 2021 18:40
Show Gist options
  • Save Clivern/0524c839cc8f9b1405b147a91370b258 to your computer and use it in GitHub Desktop.
Save Clivern/0524c839cc8f9b1405b147a91370b258 to your computer and use it in GitHub Desktop.
Python Tuple
"""
A tuple is similar to a list. The difference between the two is that we cannot change the elements of a tuple once
it is assigned whereas in a list, elements can be changed.
- We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes.
- Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
- Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
- If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
https://www.programiz.com/python-programming/tuple
http://thomas-cokelaer.info/tutorials/python/tuples.html
"""
class Tuples():
def __init__(self, elem):
self.elem = elem
def len(self):
return len(self.elem)
def sum(self):
"""Retrun the sum of all elements in the tuple."""
return sum(self.elem)
def enumerate(self):
"""Return an enumerate object. It contains the index and value of all the items of tuple as pairs."""
return enumerate(self.elem)
def max(self):
"""Return the largest item in the tuple."""
return max(self.elem)
def min(self):
"""Return the smallest item in the tuple"""
return min(self.elem)
def all(self):
"""Return True if all elements of the tuple are true (or if the tuple is empty)."""
return all(self.elem)
def any(self):
"""Return True if any element of the tuple is true. If the tuple is empty, return False."""
return any(self.elem)
def sort(self, reverse=False):
return sorted(self.elem, reverse=reverse)
def covert(self, list):
return tuple(list)
def exists(self, item):
return item in self.elem
def count(self, item):
"""Return the number of items that is equal to item"""
return self.elem.count(item)
def index(self, item):
"""Return index of first item that is equal to item"""
return self.elem.index(item)
def get(self, index):
return self.elem[index]
def get_tuple(self):
return self.elem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment