Your privacy matters: This site uses cookies to analyze site usage and provide social media features. Learn More.

Named Tuples in Python

August 28, 2014 in Python Articles

Written by John Strickler


When you need to represent a list of identical objects with different values, you start with a list of tuples. It’s an efficient way to hold a collection of related data. Tuples are like structures or records in other languages, but indexed with integers, like lists. You can build a list named people, where each element is a tuple of three elements: first name, last name, and zip code. To get the zip code for the first element, you can use people[0][2].

The problem comes when you want to read in a file where each line has 17 fields. It gets really hard to remember which index is for which field. At this point, many programmers create a class with read-only properties for this purpose, so they can say class.field (e.g., people[0].first_name, people[0].last_name, etc.). Such a class has no methods; it only exists to store the data.

It’s overkill to use a class for this purpose. Python provides an elegant solution – named tuples. A named tuple is exactly like a normal tuple, except that the fields can also be accessed by .fieldname. Named tuples are still immutable, you can still index elements with integers, and you can iterate over the elements. With a named tuple, you can say record.first_name, record.last_name, as with a class, but without the extra code of a class. There’s no need to write all the property definitions.

Creating a Named Tuple

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields. To use it, call the new class with all the values (in order) as parameters. Remember, the tuple is still immutable. You can’t change it or add fields later. All fields must be supplied.

Remember, when you need a structure with field names, use a named tuple.

Example

>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'first_name last_name zip_code')
>>> p1 = Person('Joe', 'Schmoe', '93002')
>>> p1.first_name
'Joe'
>>> p1[0]
'Joe'
>>> p1.zip_code
'92002'
>>> len(p1)
3
>>> type(p1)
<class '__main__.Person'>
>>>

Accelebrate offers private, on-site Python training.


Written by John Strickler

John Strickler
John is a long-time trainer of Accelebrate and has taught all over the US. He is a programmer, trainer, and consultant for Python, SQL, Django, and Flask.


Contact Us:

Accelebrate’s training classes are available for private groups of 3 or more people at your site or online anywhere worldwide.

Don't settle for a "one size fits all" public class! Have Accelebrate deliver exactly the training you want, privately at your site or online, for less than the cost of a public class.

For pricing and to learn more, please contact us.

Contact Us

Toll-free in US/Canada:
877 849 1850
International:
+1 678 648 3113

Toll-free in US/Canada:
866 566 1228
International:
+1 404 420 2491

925B Peachtree Street, NE
PMB 378
Atlanta, GA 30309-3918
USA

Subscribe to our Newsletter:

Never miss the latest news and information from Accelebrate:

Microsoft Partner

Please see our complete list of
Microsoft Official Courses

Recent Training Locations

Alabama

Huntsville

Montgomery

Birmingham

Alaska

Anchorage

Arizona

Phoenix

Tucson

Arkansas

Fayetteville

Little Rock

California

San Francisco

Oakland

San Jose

Orange County

Los Angeles

Sacramento

San Diego

Colorado

Denver

Boulder

Colorado Springs

Connecticut

Hartford

DC

Washington

Florida

Fort Lauderdale

Miami

Jacksonville

Orlando

Saint Petersburg

Tampa

Georgia

Atlanta

Augusta

Savannah

Idaho

Boise

Illinois

Chicago

Indiana

Indianapolis

Iowa

Ceder Rapids

Des Moines

Kansas

Wichita

Kentucky

Lexington

Louisville

Louisiana

Banton Rouge

New Orleans

Maine

Portland

Maryland

Annapolis

Baltimore

Hagerstown

Frederick

Massachusetts

Springfield

Boston

Cambridge

Michigan

Ann Arbor

Detroit

Grand Rapids

Minnesota

Saint Paul

Minneapolis

Mississippi

Jackson

Missouri

Kansas City

St. Louis

Nebraska

Lincoln

Omaha

Nevada

Reno

Las Vegas

New Jersey

Princeton

New Mexico

Albuquerque

New York

Buffalo

Albany

White Plains

New York City

North Carolina

Charlotte

Durham

Raleigh

Ohio

Canton

Akron

Cincinnati

Cleveland

Columbus

Dayton

Oklahoma

Tulsa

Oklahoma City

Oregon

Portland

Pennsylvania

Pittsburgh

Philadelphia

Rhode Island

Providence

South Carolina

Columbia

Charleston

Spartanburg

Greenville

Tennessee

Memphis

Nashville

Knoxville

Texas

Dallas

El Paso

Houston

San Antonio

Austin

Utah

Salt Lake City

Virginia

Richmond

Alexandria

Arlington

Washington

Tacoma

Seattle

West Virginia

Charleston

Wisconsin

Madison

Milwaukee

Alberta

Edmonton

Calgary

British Columbia

Vancouver

Nova Scotia

Halifax

Ontario

Ottawa

Toronto

Quebec

Montreal

Puerto Rico

San Juan

© 2013-2019 Accelebrate, Inc. All Rights Reserved. All trademarks are owned by their respective owners.