17. Tuples and multiple return values
To write a function that returns more than one value in a single call, and to unpack its result into names.
Explanation
Section titled “Explanation”- A tuple is a struct without a name: ordered values, each with a name and a type, such as
(اصغر عدد64, اكبر عدد64)(smallest, largest), with two fields or more (since 0.14.0). - You write it as the function’s return type, and return its value in parentheses:
ارجع (ص, ك). - Destructuring:
ص, ك = حدود(درجات)puts each field into a name, in order, and_is for a field you do not want. - Or you keep the whole tuple under one name and read a field with a dot:
ح.اكبر.اطبع(ح)prints the fields with their names.
# حدود قائمة درجات: أصغرها وأكبرها في نداء واحدداله حدود(درجات قائمة[عدد64]) (اصغر عدد64, اكبر عدد64): ص = درجات[0] ك = درجات[0] لكل د في درجات: اذا د < ص: ص = د اذا د > ك: ك = د ارجع (ص, ك)
درجات قائمة[عدد64] = [72, 95, 64, 88]ص, ك = حدود(درجات)اطبع("أصغر درجة: ", ص, "، وأكبر درجة: ", ك)ح = حدود(درجات)اطبع(ح)اطبع("المدى: ", ح.اكبر - ح.اصغر)_, اعلى = حدود([3, 9, 5])اطبع("الأعلى وحده: ", اعلى)حرر(درجات)A tuple can also be a list element, and لكل (for each) unpacks it on every round:
# نقاط على خريطة: قائمة صفوف، ولكل بتفكيكمواقع قائمة[(اسم نص, س عدد64, ص عدد64)] = [("البيت", 0, 0), ("المدرسة", 3, 4), ("السوق", -2, 5)]لكل (اسم, س, ص) في مواقع: اطبع(اسم, ": ", س, "، ", ص)حرر(مواقع)Exercise
Section titled “Exercise”Write a function ملخص (summary) that takes a list of ages and returns a tuple with their total (عدد64) and their average (كسر64), then print both.
Show the solution
# مجموع الأعمار ومعدلها في نداء واحدداله ملخص(اعمار قائمة[عدد64]) (مجموع عدد64, معدل كسر64): م = 0 لكل ع في اعمار: م += ع ارجع (م, كسر64(م) / كسر64(طول(اعمار)))
اعمار قائمة[عدد64] = [12, 15, 9, 20]م, ع = ملخص(اعمار)اطبع("المجموع: ", م)اطبع("المعدل: ", ع)حرر(اعمار)Common mistakes
Section titled “Common mistakes”The number of names in the destructuring does not match the number of fields in the tuple (E0490):
داله نقطة() (س عدد64, ص عدد64): ارجع (3, 4)ا, ب, ج = نقطة()Exit code: 2
In the error catalog: E0490
The fix: one name for each field, and _ for what you do not want (ا, _ = نقطة()). Note also that two tuples are not compared with == directly (E0147); compare their fields.
See also
Section titled “See also”Types: tuples and multiple return values · Functions · Structs