ben890
ben890

Reputation: 1133

enumerate is iterating of letters of strings in a list instead of elements

I'm trying to use enumerate to iterate of a list and store the elements of the list as well as use the index to grab the index of another list the same size.

Using a silly example:

animal = ['cat', 'dog', 'fish' , 'monkey']
name = ['george', 'steve', 'john', 'james']

x = []
for count, i in enumerate(animal):
    y = zip(name[count], i)
    x = x +y

Instead of producing tuples of each element of both lists. It produces tuples by letter. Is there a way to do this but get the elements of each list rather than each letter? I know there is likely a better more pythonic way of accomplishing this same task, but I'm specifically looking to do it this way.

Upvotes: 1

Views: 1097

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123520

enumerate() is doing no such thing. You are pairing up the letters here:

y = zip(name[count], i)

For example, for the first element in animal, count is 0 and i is set to 'cat'. name[0] is 'george', so you are asking Python to zip() together 'george' and 'cat':

>>> zip('george', 'cat')
[('g', 'c'), ('e', 'a'), ('o', 't')]

This is capped at the shorter wordlength.

If you wanted a tuple, just use:

y = (name[count], i)

and then append that to your x list:

x.append(y)

You could use zip() instead of enumerate() to create your pairings:

x = zip(name, animal)

without any loops required:

>>> animal = ['cat', 'dog', 'fish' , 'monkey']
>>> name = ['george', 'steve', 'john', 'james']
>>> zip(name, animal)
[('george', 'cat'), ('steve', 'dog'), ('john', 'fish'), ('james', 'monkey')]

Upvotes: 4

Anand S Kumar
Anand S Kumar

Reputation: 90979

When you use zip() it actually creates a list of tuples of corresponding elements at each index.

So when you provide strings as the input, it provides the result as list of tuples at each character. Example -

>>> zip('cat','george')
[('c', 'g'), ('a', 'e'), ('t', 'o')]

This is what you are doing, when you iterate over each element in the list and use zip.

Instead , you should directly use zip , without iterating over the elements of the list.

Example -

>>> animal = ['cat', 'dog', 'fish' , 'monkey']
>>> name = ['george', 'steve', 'john', 'james']
>>> zip(animal,name)
[('cat', 'george'), ('dog', 'steve'), ('fish', 'john'), ('monkey', 'james')]

Upvotes: 1

Related Questions