Python zip with index

Use enumerate() and zip() together in Python

In Python, enumerate() and zip() are useful when iterating over elements of iterable ( list , tuple , etc.) in a for loop.

You can get the index with enumerate() , and get the elements of multiple iterables with zip() .

This article describes the notes when using enumerate() and zip() together.

Notes on using enumerate() and zip() together

To get elements and indices from multiple lists simultaneously, you can combine enumerate() and zip() .

In this case, you need to enclose the elements of zip() in parentheses, like for i, (a, b, . ) in enumerate(zip( . )) .

names = ['Alice', 'Bob', 'Charlie'] ages = [24, 50, 18] for i, (name, age) in enumerate(zip(names, ages)): print(i, name, age) # 0 Alice 24 # 1 Bob 50 # 2 Charlie 18 

You can also receive the elements of zip() as a tuple.

for i, t in enumerate(zip(names, ages)): print(i, t) # 0 ('Alice', 24) # 1 ('Bob', 50) # 2 ('Charlie', 18) 
for i, t in enumerate(zip(names, ages)): print(i, t[0], t[1]) # 0 Alice 24 # 1 Bob 50 # 2 Charlie 18 

Note that you can use itertools.count() and zip() functions to create a non-nested form like (i, a, b) .

Источник

Understanding Enumerate and Zip Functions in Python

In this tutorial, our goal is to teach you all about the Python enumerate() and zip() functions by stepping through several examples.

The enumerate() function returns indexes of all items in iterables (lists, dictionaries, sets, etc.) whereas the zip() function is used to aggregate, or combine, multiple iterables. I know those are a bunch of big words, but our examples will help!

Python Enumerate Function

The enumerate() function in Python is used to retrieve indexes of all the items in an iterable. An iterable is a collection of items in Python such as lists, dictionaries and sets.

Though you can use the index() function to get the index of an item in an iterable, the index() function only returns the index of the first occurrence of the item. For instance, in the nums list in the script below, the integer 20 occurs three times. If you try to print the index of the integer 20, you’ll only see the index of the first occurrence of 20, the index position 2.

nums = [10,15,20,25,30,14,20,19,34,14,20,12] index_20 = nums.index(20) print(index_20)

With the enumerate() function, you can get indexes of all the items even if they occur multiple times in a list. The enumerate() function returns an object of “enumerate” type as shown in the output of the following script.

type_enum = type(enumerate(nums)) print(type_enum)

The enumerate() function returns tuples of two items where the first item corresponds to the index while the second tuple item corresponds to the actual item in the corresponding iterable. You can convert the object returned by the enumerate() function into a list of tuples containing indexes and corresponding items as shown below:

Now you can see all the indexes and their corresponding items from the nums list. Notice you can also see the indexes for the items that occur multiple times e.g. integers 20 and 14.

[(0, 10), (1, 15), (2, 20), (3, 25), (4, 30), (5, 14), (6, 20), (7, 19), (8, 34), (9, 14), (10, 20), (11, 12)]

You can use a for loop to iterate through the tuples returned by the enumerate() function as shown below where the first tuple item is accessed via index 0, while the second tuple item is accessed via index 1.

for i in enumerate(nums): print("Index =>",i[0]," - value =>", i[1])
Index => 0 - value => 10 Index => 1 - value => 15 Index => 2 - value => 20 Index => 3 - value => 25 Index => 4 - value => 30 Index => 5 - value => 14 Index => 6 - value => 20 Index => 7 - value => 19 Index => 8 - value => 34 Index => 9 - value => 14 Index => 10 - value => 20 Index => 11 - value => 12

You can also use the tuple unpacking to directly access the indexes and items in tuples returned by the enumerate() function. Here’s an example:

for i, j in enumerate(nums): print("Index =>",i," - value =>", j)
Index => 0 - value => 10 Index => 1 - value => 15 Index => 2 - value => 20 Index => 3 - value => 25 Index => 4 - value => 30 Index => 5 - value => 14 Index => 6 - value => 20 Index => 7 - value => 19 Index => 8 - value => 34 Index => 9 - value => 14 Index => 10 - value => 20 Index => 11 - value => 12

As an another example, the following script shows how you can use the enumerate() function to get all the indexes for the integer 20 in the “nums” list.

for i in enumerate(nums): if i[1] == 20: print("Value =>",i[1]," - index =>", i[0])
Value => 20 - index => 2 Value => 20 - index => 6 Value => 20 - index => 10

You can also reset the starting index for the tuples returned by the enumerate() by passing a value to the start parameter. For instance, the script below sets 8 as the starting index value for the list of tuples returned by the enumerate() function.

for i in enumerate(nums, start = 8): print("Index =>",i[0]," - value =>", i[1])
Index => 8 - value => 10 Index => 9 - value => 15 Index => 10 - value => 20 Index => 11 - value => 25 Index => 12 - value => 30 Index => 13 - value => 14 Index => 14 - value => 20 Index => 15 - value => 19 Index => 16 - value => 34 Index => 17 - value => 14 Index => 18 - value => 20 Index => 19 - value => 12

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.

Python Zip Function

The zip() function in Python is used to aggregate multiple iterables. The zip() function returns a list of tuples where each tuple contains the items from the matching indexes of the original iterables. This is best explained with an example.

The script below contains three lists: names , ages , and genders . Each list has 5 items. The lists are aggregated via the zip() function. If you print the list of tuples returned by the zip() function you’ll see that each tuple item contains items from the matching indexes in the original lists. For instance, the first tuple contains three items: ‘john’, 20, ‘male’. These three items occur at 0th indexes of the names , ages , and genders list, respectively.

names = ["john", "nick", "sally", "Elizabeth", "Mike"] ages = [20, 25, 35, 22, 29] genders = ["male", "male", "female", "female", "male"] records = list(zip(names, ages, genders)) print(records)
[('john', 20, 'male'), ('nick', 25, 'male'), ('sally', 35, 'female'), ('Elizabeth', 22, 'female'), ('Mike', 29, 'male')]

Just as you saw with the enumerate() function, you can use tuple unpacking to get the individual items from the tuples returned by the zip() function. Here’s an example:

for name, age, gender in zip(names, ages, genders): print("Name=>", name, " -Age=>", age, " -Gender=>", gender)
Name=> john -Age=> 20 -Gender=> male Name=> nick -Age=> 25 -Gender=> male Name=> sally -Age=> 35 -Gender=> female Name=> Elizabeth -Age=> 22 -Gender=> female Name=> Mike -Age=> 29 -Gender=> male

In some cases, the iterables being aggregated, or combined, using the zip() function contain an unequal number of items. In such cases, only those items from multiple iterables are aggregated that correspond to the items in the smallest iterable.

For instance, in the script below the genders list only contains 2 items. Using the zip() function to aggregate the names , ages , and genders lists in the following case will only return two tuples containing items from the 0th and 1st indexes of the names , ages , and genders lists.

names = ["john", "nick", "sally", "Elizabeth", "Mike"] ages = [20, 25, 35, 22, 29] genders = ["male", "male"] records = list(zip(names, ages, genders)) print(records)
[('john', 20, 'male'), ('nick', 25, 'male')]

Combining Enumerate with Zip

You can also call the enumerate() function on the output returned by the zip() function. In such cases, the enumerate() function will return tuples where the items at the first index in the tuple will correspond to the indexes of the tuples returned by the zip() function and the items at the second index will correspond to the actual tuple returned by the zip() function. This sounds a little complicated so follow this example to see how you can use the enumerate() and zip() functions together.

names = ["john", "nick", "sally", "Elizabeth", "Mike"] ages = [20, 25, 35, 22, 29] genders = ["male", "male", "female", "female", "male"] for i, record in enumerate(zip(names, ages, genders)): print("Index=>", i," -Name=>", record[0], " -Age=>", record[1], " -Gender=>", record[2])
Index=> 0 -Name=> john -Age=> 20 -Gender=> male Index=> 1 -Name=> nick -Age=> 25 -Gender=> male Index=> 2 -Name=> sally -Age=> 35 -Gender=> female Index=> 3 -Name=> Elizabeth -Age=> 22 -Gender=> female Index=> 4 -Name=> Mike -Age=> 29 -Gender=> male

Notice how we now have a table of the lists with an associated index. If you found this tutorial helpful, be sure to subscribe using the form below. My goal is to make sure you’re getting the most out of Python so you can intelligently tackle your next programming project.

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.

Источник

How to use Python’s enumerate and zip to iterate over two lists and their indices.

The Python Cookbook (Recipe 4.4) describes how to iterate over items and indices in a list using enumerate . For example:

alist = ['a1', 'a2', 'a3'] for i, a in enumerate(alist): print i, a 

zip — Iterate over two lists in parallel ¶

I previously wrote about using zip to iterate over two lists in parallel. Example:

alist = ['a1', 'a2', 'a3'] blist = ['b1', 'b2', 'b3'] for a, b in zip(alist, blist): print a, b 

enumerate with zip¶

Here is how to iterate over two lists and their indices using enumerate together with zip:

alist = ['a1', 'a2', 'a3'] blist = ['b1', 'b2', 'b3'] for i, (a, b) in enumerate(zip(alist, blist)): print i, a, b 
  • An example using Python’s groupby and defaultdict to do the same task— posted 2014-10-09
  • python enum types— posted 2012-10-10
  • Python data object motivated by a desire for a mutable namedtuple with default values— posted 2012-08-03
  • How to sort a list of dicts in Python— posted 2010-04-02
  • Python setdefault example— posted 2010-02-09
  • How to conditionally replace items in a list— posted 2008-08-22

Comments

If you’re working with last lists and/or memory is a concern, using the itertools module is an even better option.

from itertools import izip, count alist = ['a1', 'a2', 'a3'] blist = ['b1', 'b2', 'b3'] for i, a, b in izip(count(), alist, blist): print i, a, b 

yields the exact same result as above, but is faster and uses less memory.

#2 Jeremy Lewis commented on 2009-05-29 :

>>> def foo(): . for i, x, y in izip(count(), a, b): . pass . >>> def bar(): . for i, (x, y) in enumerate(zip(a, b)): . pass . >>> delta(foo) 0.0213768482208 >>> delta(bar) 0.180979013443 

where a = b = xrange(100000) and delta(f(x)) denotes the runtime in seconds of f(x).

#3 Eliot commented on 2009-05-29 :

Jeremy,
Thanks for the tip and the clear example and demonstration of the performance benefit. I had heard of itertools but have not really used it. It was great to talk to you today and I hope I can talk to you again soon.

Thanks for the zip example, I grok it now.

#5 Jesus Carrero commented on 2011-09-11 :

Jeremy, Thanks for the example, It is very helpful.

#6 Nitin commented on 2011-11-01 :

I have set of n set, each with different number of elements I wanted to find all possible combinations of n elements, one from each set. Consider two sets (e1,e2,e3) (e4,e5)

output required is as follows

(e1,e4) (e1,e5) (e2,e4) (e2,e5) (e3,e4) (e3,e5) 

I do not know the number of such sets in advance.

#7 Eliot commented on 2011-11-01 :

#8 S commented on 2012-07-09 :

In order to use zip to iterate over two lists — Do the two lists have to be the same size? What happens if the sizes are unequal? Thanks.

#9 Tim commented on 2012-10-29 :

Thx man helped me alot nice example btw

#10 matt commented on 2013-02-08 :

re:#8, unequal list length: the result is truncated to the shorter list. See below for a discussion of how to use the longest list instead: http://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length

short answer for py2.6+: use «map(None, alist, blist)»

dunno what the equivalent is in py3+

when iterating through unequal length lists using itertools

if items[0] is not None and items[1] is not None:

if items[0] is None and items[1] is None:

is ther any other better way to give previous value if None occurs for any field.

Very useful page with clear examples, thanks.

Saltycrane logo

  • Twitter
  • Github
  • Stack Overflow
  • Atom Feed

Источник

Читайте также:  Кожа питона для обуви
Оцените статью