What is a Python tuple What are the advantages of tuple over list

Functional Programming - Tuple


Advertisements


Previous Page

Next Page

A tuple is a compound data type having a fixed number of terms. Each term in a tuple is known as an element. The number of elements is the size of the tuple.

Program to define a tuple in C#

The following program shows how to define a tuple of four terms and print them using C#, which is an object-oriented programming language.

Live Demo

using System; public class Test { public static void Main() { var t1 = Tuple.Create(1, 2, 3, new Tuple<int, int>(4, 5)); Console.WriteLine("Tuple:" + t1); } }

It will produce the following output −

Tuple :(1, 2, 3, (4, 5))

Program to define a tuple in Erlang

The following program shows how to define a tuple of four terms and print them using Erlang, which is a functional programming language.

Live Demo

-module(helloworld). -export([start/0]). start() -> P = {1,2,3,{4,5}} , io:fwrite("~w",[P]).

It will produce the following output −

{1, 2, 3, {4, 5}}

Advantages of Tuple

Tuples offer the following advantages −

  • Tuples are fined size in nature i.e. we can’t add/delete elements to/from a tuple.

  • We can search any element in a tuple.

  • Tuples are faster than lists, because they have a constant set of values.

  • Tuples can be used as dictionary keys, because they contain immutable values like strings, numbers, etc.

Tuples vs Lists

TupleList
Tuples are immutable, i.e., we can't update its data.List are mutable, i.e., we can update its data.
Elements in a tuple can be different type.All elements in a list is of same type.
Tuples are denoted by round parenthesis around the elements.Lists are denoted by square brackets around the elements.

Python Lists Vs Tuples

In this article we will learn key differences between the List and Tuples and how to use these two data structure.

Lists and Tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be of any type including the nothing type defined by the None Keyword.

Lists and Tuples are similar in most context but there are some differences which we are going to find in this article.


Python Tuple

In this article, you'll learn everything about Python tuples. More specifically, what are tuples, how to create them, when to use them and various methods you should be familiar with.