Showing posts with label Python tuple. Show all posts
Showing posts with label Python tuple. Show all posts

Thursday, May 16, 2024

Tuple in Python With Examples

Tuple in Python is one of the sequence data type that can store a group of elements. Tuple is similar to Python list with one notable difference that the Tuple is immutable where as list is mutable.

Once a tuple is created you can’t modify its elements. So performing operations like insert(),remove(), pop(), clear() are not possible on tuples.

Some of the important points about Python Tuple are-

  1. A tuple can store elements of different types.
  2. Tuple maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
  3. Tuple is immutable. So, it is not possible to change content of a tuple.
  4. Tuples can be indexed (both positive and negative) and sliced.

In this article we’ll see some of the features of the Python tuples with examples, methods in Tuple and functions that can be used with tuple.


Creating a tuple

1. In Python tuple is created by grouping elements with in parenthesis (), where the elements are separated by comma. It is the preferred way and also necessary in some scenarios.

# empty tuple
t = ()
print(t)

# tuple with items having different types
t = (12, 54, 'hello!')
print(t)

# tuple containing lists
t = ([1, 2, 3], [4, 5, 6])
print(t)

Output

()
(12, 54, 'hello!')
([1, 2, 3], [4, 5, 6])

Here note that though Tuple itself is immutable but it can contain mutable objects like list.

2. When a tuple with one item is constructed value should be followed by a comma (it is not sufficient to enclose a single value in parentheses).

t = (1)
print(type(t))

t = (1,)
print(type(t))

Output

<class 'int'>
<class 'tuple'>

As you can see, in first assignment type of t is integer not tuple. In the second assignment when value is followed by comma, the type of t is tuple.

3. You can also create a tuple using tuple() type constructor. An iterable can be passed as an argument to create a tuple, if no argument is passed then an empty tuple is created.

t = tuple()
print(t)
print(type(t))

Output

()
<class 'tuple'>

When argument is passed-

#Tuple as argument
t = tuple((1,2,3)) 
print(t)
print(type(t))

#List as argument
t = tuple([1, "Test", 4.56])
print(t)
print(type(t))

Output

(1, 2, 3)
<class 'tuple'>
(1, 'Test', 4.56)
<class 'tuple'>

Tuple packing and unpacking

Tuple can also be created without using parenthesis, it is known as tuple packing.

t = 3, 4, 'Hello'
print(t)
print(type(t))

Output

(3, 4, 'Hello')
<class 'tuple'>

You can also do tuple unpacking by assigning tuple items to variables, unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.

#packing
t = 3, 4, 'Hello'
print(t)
print(type(t))

#unpacking
x, y, z = t
print('x',x)
print('y',y)
print('z',z)

Output

(3, 4, 'Hello')
<class 'tuple'>
x 3
y 4
z Hello

Accessing tuple elements using index

Tuple in python uses index starting from 0 to (tuple_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes till tuple_length.

Here is an example showing tuple indexing for the stored elements.

To access an element of the tuple you can pass the corresponding index in the square brackets. For example to access the 5th element in a tuple you will pass tuple[4], as index starts from 0.

t = (2, 3, 6, 7, 9)
# 1st element
print(t[0])

#last element
print(t[4])

#last element
print(t[-1])

#first element
print(t[-5])

Output

2
9
9
2

Trying to pass index beyond the index range of the tuple results in ‘index error’. For example here is a tuple having 5 elements so index range for the tuple is 0..4, trying to access index 5 results in an error.

t = (2, 3, 6, 7, 9)
print(t[6])

Output

IndexError: tuple index out of range

Slicing a tuple

Just like string slicing you can do tuple slicing too which returns a new tuple.

Format of tuple slicing is as follows-

Tupleobject[start_position: end_position: increment_step]
  • start_position is the index from which the slicing starts, start_position is included.
  • end_position is the index at which the tuple slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

t = [2, 4, 6, 8, 10]
print(t[1:len(t):2]) #[4, 8]


t = [2, 4, 6, 8, 10]
print(t[::])#[2, 4, 6, 8, 10]
print(t[-3:])#[6, 8, 10]

Methods in tuple

Tuples provide the following two methods-

  • count(x)- Returns the number of items x
  • index(x)- Returns the index of the first item that is equal to x

Functions that can be used with tuple

  • len- The len() function returns the number of items of a sequence
  • min- The min() function returns the minimum element in a sequence
  • max- The max() function returns the maximum element in a sequence
  • sorted- Return a new sorted list from the items in iterable.

Operators used with tuples

Tuples can be used with the following operators which result in a creation of new tuple.

  • + (concatenation)
  • * (replication)
  • [] (slice)

Iterating a tuple

You can iterate all elements of a tuple using for or while loop.

1. Using for loop

t = [3, 1, 9, 2, 5]
for i in t:
  print(i)

Output

3
1
9
2
5

2. Using while loop

t = [3, 1, 9, 2, 5]
i = 0;
while i < len(t):
  print(t[i])
  i += 1

Output

3
1
9
2
5

del keyword with tuple

Since tuple is immutable so elements can’t be modified or removed from a tuple but tuple itself can be deleted entirely using del keyword along with tuple instance.

t = [3, 1, 9, 2, 5]

print(t)
del t
print(t)

Output

[3, 1, 9, 2, 5]
   print(t)
NameError: name 't' is not defined

Second print(t) statement results in an error as tuple t is already deleted.

That's all for this topic Tuple in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Named Tuple in Python
  2. List Comprehension in Python With Examples
  3. String Length in Python - len() Function
  4. Python Functions : Returning Multiple Values
  5. Constructor in Python - __init__() function

You may also like-

  1. Python while Loop With Examples
  2. Multiple Inheritance in Python
  3. Installing Anaconda Distribution On Windows
  4. Python Program to Display Fibonacci Series
  5. Java Multithreading Interview Questions And Answers
  6. Dependency Injection in Spring Framework
  7. String in Java Tutorial
  8. Volatile Keyword in Java With Examples

Thursday, January 16, 2020

Named Tuple in Python

In this post we’ll see what are named tuples in Python and how to use them.

In a tuple you can store arbitrary elements and access them using index. Now, consider the scenario where tuple is storing a lots of fields, remembering field ordering and accessing them using index becomes quite a task and it is also less readable. In such scenarios named tuple is handy.


Python named tuple

A named tuple is a custom tuple data type which provides ability to refer the items in the tuple by both item names as well as by index position.

A named tuple is similar to plain tuple providing the same performance and the immutability feature.

Creating named tuple

To create a named tuple you need to import named tuple from the Collections module.

from collections import namedtuple

Here namedtuple() is a factory function that returns a tuple class.

Syntax for creating named tuple

namedtuple(typename, field_names)

Here typename is the name of the new tuple subclass which is used to create tuple-like objects.

field_names represent fields which are stored in the named tuple. They can be provied as a sequence of strings like ['field1', 'field2'] or as a single string with each fieldname separated by whitespace and/or commas, for example 'field1 field2' or 'field1', 'field2'.

For example-

Employee = namedtuple('Employee',['id', 'name','age'])

Here named tuple Employee is created which can store field id, name and age.

You can also provide fieldnames as a single string separated by white space.

Employee = namedtuple('Employee', 'id name age')

Python named tuple example

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
e2 = Employee('124', 'Lisa', '31')

# Access using index
print('Employee Age', e1[2])

# Access using field name
print('Employee Name', e2.name)

#iterating
for emp in [e1, e2]:
  print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Lisa
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

Use cases for named tuple usage

1. You have a list in Python that stores objects of same type. Rather than creating a class with the fields and then creating objects of that class and storing them in the list you can create a named tuple which is much easier to create.

Here is the same example as above but uses list to store named tuples.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')
#list
employees = []
# storing named tuples
employees.append(Employee('123', 'Joe', '28'))
employees.append(Employee('124', 'Lisa', '31'))

# Access using index
print('Employee Age', employees[0][2])

# Access using field name
print('Employee Name', employees[0].name)

# iterate list
for emp in employees:
    print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Joe
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

2. You have a CSV file with a record structure. You can create a similar record structure using named tuple and read records into named tuple directly.

import csv
from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

for emp in map(Employee._make, csv.reader(open("F:\\NETJS\\employee.csv", "r"))):
    print(emp.id, emp.name, emp.age)

Here note that _make method of the named tuple is used which is a class method that makes a new instance from an existing sequence or iterable.

Methods in named tuple

In addition to the methods inherited from tuples, named tuples support three additional methods.

1. _make(iterable)- Class method that makes a new instance from an existing sequence or iterable. We have already seen an example of this method.

2. _asdict()- Return a new dict which maps field names to their corresponding values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
print(e1._asdict())

Output

OrderedDict([('id', '123'), ('name', 'Joe'), ('age', '28')])

3. _replace(**kwargs)- Return a new instance of the named tuple replacing specified fields with new values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', 28)
print(e1)
print(e1._replace(age=30))

Output

Employee(id='123', name='Joe', age=28)
Employee(id='123', name='Joe', age=30)

That's all for this topic Named Tuple in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Concatenating Lists in Python
  2. List Comprehension in Python With Examples
  3. Class And Object in Python
  4. Passing Object of The Class as Parameter in Python
  5. Abstraction in Python

You may also like-

  1. Ternary Operator in Python
  2. Check if String Present in Another String in Python
  3. User-defined Exceptions in Python
  4. Convert String to int in Python
  5. ReentrantLock in Java Concurrency
  6. How HashMap Works Internally in Java
  7. Generics in Java
  8. Array in Java With Examples