A carnival ride called Zipper.
Take a wild ride with Dart’s Zip and Reduce! Photo by Jake Weirick on Unsplash

Zip and Reduce in Dart

As a Python developer who is also writing Dart, there are a few things I was missing when developing in Dart. One of those was the mighty zip function. The zip function in Python is really handy for combining two or more lists into a list of lists. (actually python returns an iterator of tuples, but it serves the same purpose) This zipping operation is pretty common in data science when cleaning up data.

After a little digging, I found the zip function in Dart. It’s in a package called Quiver. I’m not sure if it is a core package written by Google or not, but it has a couple handy utility libraries. Zip is in the iterables library, well, because it works on iterables. At first I had some trouble installing the library. But once I found the Quiver page on pub.dev, it was really clear how to install it.

Add this to your pubspec.yaml file.

Run this in the command line to get the package.

At the top of your dart file add:

Zipping With Zip()

Let’s start with two lists of integers:

Python’s:

In Dart you would use the zip() function like this:

Returns [[1, 5], [2, 6], [3, 7]]

Notice that I added the toList() method at the end. This gives us a list of lists, instead of the iterable of lists that it would normally return. Also take note that the integer 9 in int_list_2 didn't get zipped. That's because it bases the zip on the shortest list only.

The Reduce() Method

Reduce is another method which is often mentioned along with map()and where() (which I covered here). Reduce() can be used to sum up a list of numbers. I don't find myself using it much in Python, but it does come in handy every once in a while. It takes the first element in a list, does something to it, keeps the value and then does the same thing with the next element. And it keeps on going until it reaches the end of the list.

Here’s that list again:

Python’s:

In dart the reduce() looks like this:

Returns 10
In this case 10 is sum of the all the integers in the list.

Fun with Dart (and Flutter)

I’ve found that being comfortable with Lists, Maps and other iterables to be super import in developing applications and pipelines. And they can be fun once you get a good grasp of them.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Python Is Rad

Python Is Rad. I’m a software engineer with an addiction to building things with code. https://twitter.com/PysparkIsRad