_make method of namedtuple class of collections module in Python

Method Name:

_make

Method Signature:

_make(iterable)

Parameter:

iterable – An iterable from which a namedtuple is created. The iterable can be another namedtuple as well.

 

Return Value:

Returns the namedtuple, which is a copy of the parameter iterable.

Overview:

  • The _make() method of the namedtuple is a class method.
  • The method creates an instance of a named tuple type.
  • The Python examples below create named tuples from an iterable and as well as from a named tuple using the _make() method.

 

Example – Create a namedtuple from an iterable using _make() function:

# Example Python program that clones a namedtuple from another

# namedtuple using the class method namedtuple._make()

import collections as coll

 

# Create a type coord that represents a point on Earth's surface

coord = coll.namedtuple("coord", "city, lat, long");

 

# Create a coord for NYC

nyc = ["NYC", 40.73, -73.93];

 

# Clone a coord from an existing iterable

nycCopy = coord._make(nyc);

print("Cloned coord for NYC:");

print(nycCopy);

 

Output:

Cloned coord for NYC:

coord(city='NYC', lat=40.73, long=-73.93)

 

 

Example – Create a namedtuple from an existing one using _make() function:

# Example Python program that clones a namedtuple from another

# namedtuple using the class method namedtuple._make()

import collections as coll

 

# Create a type coord that represents a point on Earth's surface

coord = coll.namedtuple("coord", "city, lat, long");

 

# Create a coord for Quito

quito = coord("Quito", -0.18, -78.46)

 

# Clone a coord from an existing coord

quito1 = coord._make(quito);

print("Cloned coord for Quito:");

print(quito1);

 

Output:

Cloned coord for Quito:

coord(city='Quito', lat=-0.18, long=-78.46)

 


Copyright 2024 © pythontic.com