Combining arrays of tuples
Let’s say you’ve got an array of tuples like this:
tuples = [[1, 2], [3, 4], [5, 6]]
and another array of tuples like this:
more_tuples = [[7, 8], [9, 10]]
What you want is for all five tuples to live happily in one array together, but when you do this:
all_the_tuples = tuples.push(more_tuples)
Uggggggghhhhhhhhhhh this happens:
[[1, 2], [3, 4], [5, 6], [[7, 8], [9, 10]]]
push
has combined the two arrays, sure, but it’s also left the second array in tact in the form of those extra brackets around 7, 8 and 9, 10.
Oh but you. You’re clever. You know how to flatten
.
all_the_tuples.flatten
Whoops:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
No more tuples. Just an array. (Good thing you didn’t flatten!
.)
Oh! Ohhhhh! But you can add an optional argument to flatten
to “determine the level of recursion”. You’re not exactly sure what this means, but you push up your sleeves and get to work anyway.
all_the_tuples.flatten(1)
doesn’t do what we wanted though. It returns [1, 2, 3, 4, 5, 6, [7, 8], [9, 10]]
. Whomp.
You just start typing numbers in:
all_the_tuples.flatten(2)
does the same as flatten
. So does all_the_tuples.flatten(-1)
. (You also try 3 for good measure. Same result. You wonder whether or not to admit to this later.)
At this point you push the computer away from your hands and lay your face on the table. How much time have you spent on this? All you want is to ADD two arrays of tuples into one thing.
Oh wait.
Hang on a minute.
tuples + more_tuples
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
You laugh like an insane person at the simplicity of this, but look at all you learned! Enjoy your victory sip.