11 – Zip and Enumerate

Looking back at our list of cargo, notice each element is a tuple of size two. Iterating through a list with multiple values, can be pretty helpful. It’s actually really easy to combine and split lists like this. If we originally started, with these two separate lists, items and weights, and wanted to combine them to create a list, like manifest, we can use a built-in function called zip. Zip, returns an iterator. So, we need to convert it to a list to see the elements. Or, iterate through it with a for loop, if we want to print the values, similar to range. You could also unpack each tuple in a for loop like this. In addition to zipping two lists together, you can also unzip a list using an asterisk. For example, using the manifest lists like this, you can separate it into an items and weights list, like this. The next function we’ll look at, is enumerate. Many times, you’ll find it useful to iterate through the values of a list, along with the index. This is one way you could do it. This uses a for loop to iterate through a list of tuples containing the index, and value of each item in the list. The indices are created by getting a range object from zero, to the length of items minus one, and zipping that with the values in items. Enumerate, is a special built-in function that makes this a lot simpler. Enumerate returns these tuples, containing the indices and values of a list, in an iterable for you. You’ll be getting some practice using Zip and Enumerate and see how helpful they can be, in the following quiz section.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading