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

Python Is Rad
2 min readApr 27, 2020

--

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.

dependencies:
quiver: ^2.1.3

Run this in the command line to get the package.

pub get

At the top of your dart file add:

import 'package:quiver/iterables.dart';

Zipping With Zip()

Let’s start with two lists of integers:

var int_list_1 = [1, 2, 3, 4];
var int_list_2 = [5, 6, 7, 8, 9];

Python’s:

zipped = zip(int_list1, int_list_2)

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

var zipped = zip([int_list_1, int_list_2]).toList();

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:

var int_list_1 = [1, 2, 3, 4];

Python’s:

reduced = functools.reduce(lambda value,element : value+element, int_list_1)

In dart the reduce() looks like this:

var reduced = int_list_1.reduce((value, element) => value + element);

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.

--

--

Python Is Rad

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