Search code examples
pythonlistenumerate

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.


Solution

  • 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')]