diff --git a/Nim-for-Python-Programmers.md b/Nim-for-Python-Programmers.md index 8828be7..ba44be1 100644 --- a/Nim-for-Python-Programmers.md +++ b/Nim-for-Python-Programmers.md @@ -185,13 +185,27 @@ A [very detailed comparison](https://scripter.co/notes/string-functions-nim-vs-p ### Python tuples -Nim Tuples are close to Python namedtuples, see [manual](http://nim-lang.org/docs/manual.html#types-tuples-and-object-types). -Use Nim arrays: +Nim Tuples are a lot like Python namedtuples in that the tuple members must have names in the type specification. However, they can be constructed and destructured without naming the fields. Also, you can have anonymous tuple types. See [manual](http://nim-lang.org/docs/manual.html#types-tuples-and-object-types) for a more in depth look at tuples. + +```Nim +var a = ("hi", "there") +echo a[0] # hi + +proc swap(tup: tuple[a: int, b: float]): tuple[c: float, d: int] = + (tup.b, tup.a) + +echo swap((1, 3.14) # (c: 3.14, d:1) + +let c, d = swap(8, 4.2) +``` + +In some cases where you might have used a tuple in Python, Nim Arrays can be used if you don't care what the fields are named. However, unlike tuples, arrays can only have one element type: + ``` Nim var a = ["hi", "there"] var b = [1, 2, 3] -echo b[1] -var c = ["hi", 1] # no mixed types please +echo b[1] # 2 +var c = ["hi", 1] # Error: type mismatch (no mixed types allowed in arrays) ``` ### Python lists