Skip to main content

Tuple data structure in Python



Tuple is a linear data structure which more or less behaves like a python list but with a really important difference, that a tuple is immutable. Immutable means that this structure can't be changed after it has been created, it can't be mutated if I may.
Tuples being immutable are more memory efficient than list as they don't over allocate memory. Okay, so what this means is, when a list is created it takes up and reserves extra spaces of memory than needed for the original elements as new elements might be added to the list later and allocating memory on every addition would be quite inneficient but tuples, once created surelly won't change the numbers of elements in it later on, so it allocates exactly how much memory is needed.
Almost all the list operations work for tuples except the ones which mutate it, for example, insert, append, remove etc.
Declaring a tuple :
Tuples can be initialise in a manner similar to list,


But there's an important catch to it, if you declare a tuple that has a single element like this, t = (1) ,then Python is going to recogonise it as a single element and not a tuple.



To declare a tuple with single element, a " , "(comma) needs to be added before putting the closing bracket. As it is also said in the Python docs, its the commas that make the tuple, not the brackets.
t = (1,)
Now it will recogonise this as a singleton tuple(tuple containing one element).

Important tuple methods -
1) "in" operator

     This is used to check wether something exists in a tuple or not and returns a boolean value.


2)  len()

Return the length of the tuple



3) min() and max()

These both functions respectivelly return the minimum or the maximum value in a tuple


4) count()

Returns the number of times an element appears in the tuple


5) sorted()

Tuples can also be sorted but as they are immutable, it does not happen in place, that means the sorted method creates and returns a new list which is the sorted version of the original one.


Comments

  1. Great Post!
    It is quite comprehensive and very easy to understand!

    ReplyDelete

Post a Comment

Popular Posts

Lambda functions in Python

Lambda functions are simply functions that don't have a name. They are also called anonymous functions and are pretty useful for certain cases. They are extensively used in functional programming . Lambda expression is useful for creating small, one time use functions though the functions can also be given a name. It can have multiple arguments but just a single expression as the function body. The basic syntax to create a lambda function is lambda arguments: function body For example lambda x : x **2 This function takes in x and returns x 2 . Here, lambda is the keyword, x is the argument and the expression after the colon is the function body. These functions can also be given a name, sqr = lambda x : x **2 sqr(5) #output : 25 Multiple arguments can also be provided lambda x,y: x * y or lambda x,y,z: x*y*z These functions when given a name are equivalent to the functions defined by using the def keyword. For example def solve_quad(a,b,c): d = b**2 - (4*a*c) x1 ...

Evaluating expressions using Stacks | Dijkstra's Two-Stack Algorithm

We are going to look at Dijkstra's two-stack algorithm and see how it's implemented. This algorithm is used to evaluate infix expressions. It uses stacks at its core, so if you don't know about stacks or if you'd want to learn more about them, click this link There are three types of expressions, Infix : Infix expressions are the ones where the operators are used between values, like a + b - c . Postfix : These are the expressions where operators are written after the values, like a b c +- , this translates to a + b - c in infix. Prefix : In these expressions, the operators are written before the values, for example + - a b c . This expression will also be equal to a + b - c in infix. Okay, so what this algorithm does is evaluate expressions like ( ( 3 + 4 ) * 83 ) . It starts by breaking down this expression into a list of stings and create two empty stack, one for housing the values and other for the operators. Then we go through the list one by one. Whenev...

Balanced Brackets | Stacks

In this post we will explore and implement an algorithm which helps us verify that if the brackets are balanced or validly used. This is a very important application of stacks as a lot of programming languages use brackets very extensively in their syntax and one of the job of a compiler is to check if the brackets are balanced or not. For simplicity's sake we will just use a list with the methods append() and pop(). This will help us emulate a stack without actually needing to implement it. If you want to, you can go and learn about stacks on this link . A set of brackets can be called balanced if all of the brackets in it are properly matched. Examples of balanced brackets : (([]{}{})) ({{}}[]) Examples of unbalanced brackets : (([)]) {{}]}]]) So now getting to the algorithm, what we simply do is that we go through a string of brackets and check that for every closing bracket there is a properly nested opening bracket. This is how we do it - Convert the input string into a...

Random Numbers in Java

In this post we will go through the basics of generating random numbers and also see how they can be generated within a range along with best practices. Java provides support to either generate random numbers through java.lang.Math package or java.util.Random . Using java.lang.Math There exists a static method inside this class, Math.random . It is very convenient to use and returns a double between the range 0.0 and 1.0 i.e. it returns a floating point number between 0 and 1. public static void main(String[] args){ double randNum = Math.random(); System.out.println(randNum); } Random number within a range - To generate a random number within a range we need to further process the number returned by Math.random() public static void main (String[] args){ double min = 10.0; double max = 100.0; double randNum = randRange(min, max); System.out.println(randNum); } public static double randRange(double min, double max){ double x = (Math.rando...

Kattis | The coding platform

Recently I came across a new website for competitive coding, Kattis and I love it. It is such an amazing platform and has a plethora of question along with multiple long duration contests. The quality of questions is also good and the interface is also very intutive. Follow this link to go to Kattis .

Fast Multiplication of Long Integeres | Karatsuba's Algorithm

This article is divided into 3 parts, so feel free to skip around to the part you find useful - Need for the algorithm Intuition and Algorithm Implementation Need for the algorithm Multiplication is an elementary concept known to all of us since a very early age. But multiplication of very large numbers becomes a difficult problem that can't be solved mentally unless you're a mathematical genius and hence we use calculators and computers. Computers too can efficiently multiply numbers but as the length of digits of the number increases, the time complexity also increases along with it quadratically. To calculate the product of humongous numbers we need a better algorithm. Any algorithm that even slightly increases the runtime will prove to be very beneficial for large values of n, say 100000. Karatsuba multiplication algorithm brings down the number of operations by a factor of one and gives a huge boost. Intuition and Algorithm Okay so, to boost up the speed of...

Coding questions on Stack and Queue

If you want to learn about Stack or Queue, follow the link to the tutorials- Queue Stack Questions- Maximum Element Equal Stacks Balanced brackets Simple Text Editor Queue using two stacks Castle on the grid Stock Span Problem Celebrity Problem Next greater element

Stack

Stack So, now we're going to talk about stack , a linear data structure and also we will see its implementation. In another post which will be linked below later will discuss its uses. So what is a stack ? Visualise a pile of coins or a stack of trays put one over the other. The item that has been put at the last has to be removed first as it is over all the other items. Hence, it is a data structure that works on LIFO (Last in First out) principle. Which simply means that the element that has been added the last will be removed first. It is a very useful data structure and has several applications like expression evaluation and HTML validat or or a bracket matching verifier . In this data structure we only have operations that take their effect only at one end of the list. Both, the front or the end of a list can be used to implement it but using the tail(back-end) of the list is more efficient. The main operation or methods on a stack are - Push : Adds element at the...

Divide and Conquer

Divide and Conquer Divide and Conquer is an algorithmic paradigm used in many problems and algorithms . Some of the most common algorithms use divide and conquer principle and are highly effective. A Divide and Conquer algorithm solves a problem in 3 steps : Divide: Break the given problem into subproblems of same type. Conquer: Recursively solve these subproblems Combine: Appropriately combine the answers It starts of by breaking down a problem into multiple parts that are simple enough to be solved and then all these subparts are solved individually. For the last part , the algorithm combines all the solutions into one. Some common examples of Divide and Conquer in algorithms are - Binary Search Merge Sort Quick Sort Divide and Conquer is the principle applied to recursion and thus it is a very important technique and is of immense use for programmers. Resources - Wikipedia Technical details