[Python] Tuples

Python provides another useful built-in type: tuples. Tuples are used to store related pieces of information. Consider this example involving latitude and longitude:

>>> AngkorWat = (13.4125, 103.866667)
>>> print(type(AngkorWat))
<class 'tuple'>
>>> print("Angkor Wat is at latitude: {}".format(AngkorWat[0]))
Angkor Wat is at latitude: 13.4125
>>> print("Angkor Wat is at longitude: {}".format(AngkorWat[1]))
Angkor Wat is at longitude: 103.866667

 

Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indexes (for example AngkorWat[0] and AngkorWat[1]). Unlike lists, tuples are immutable. You can't add and remove items from tuples, or sort them in place. 

 

Why Tuples?

Why do we have tuples if they're like lists with less features? Tuples useful when you have two or more values that are so closely related that they will always be used together, like latitude and longitude coordinates.

Tuples can be used to assign multiple variables in a compact way:

>>> dimensions = 52, 40, 100 
>>> length, width, height = dimensions 
>>> print("The dimensions are {}x{}x{}".format(length, width, height))
The dimensions are 52x40x100
world_heritage_locations = {(13.4125, 103.866667): "Angkor Wat",
                            (25.73333, 32.6): "Ancient Thebes",
                            (30.330556, 35.4433330): "Petra",
                            (-13.116667, -72.583333): "Machu Picchu"}

 

Notice that the values assigned to the tuple dimensions aren't surrounded with parentheses as previous examples were. The parentheses are optional when making tuples, and programmers frequently omit them if parentheses don't clarify the code.

 

Tuple Unpacking

In the second line, three variables are assigned from the content of the tuple dimensions. This is called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into multiple variables without having to access them one by one and make multiple assignment statements.

In this example, if we won't need to use dimensions directly, we could shorten those two lines of code into a single line that assigns three variables in one go!

length, width, height = 52, 40, 100

 

Returning Tuples

def first_and_last(sequence):
    """returns the first and last elements of a sequence"""
    return sequence[0], sequence[-1]

>>> first_and_last(["Spam", "egg", "sausage", "Spam"])
('Spam', 'Spam')

A function that returns a tuple can also be used to assign multiple variables:

>>> start, end = first_and_last(["Spam", "egg", "sausage", "Spam"])
>>> print(start)
Spam
>>> print(end)
Spam
def hours2days(_hours):
    days = _hours//24
    hours = _hours%24
    return days, hours
     
hours2days(24) """(1, 0)"""
hours2days(25) """(1,1)"""
hours2days(10000)  """(416, 16)"""

 

posted @   Zhentiw  阅读(465)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-11-27 [AngularFire 2] Protect Write Access Using Security Rules
2015-11-27 [Javascript] Array methods in depth - slice
2015-11-27 [ES6] ... spread operator
2015-11-27 [AngularJS] New in Angular 1.5 ng-animate-swap
2014-11-27 [AngularJS] TweenList 3D + AngularJS Animate
2014-11-27 [AngularJS] Adding custom methods to angular.module
点击右上角即可分享
微信分享提示