this gives syntax error, why would it give ?

[index, each for index,each in enumerate(names)]

Recommended Answers

All 8 Replies

>>> names = ['Google', 'Apple', 'Microsoft']
>>> for index,item in enumerate(names):
        print index,item

0 Google
1 Apple
2 Microsoft

this way i get it to work but i was having problem with list compression..

Ok here is list comprehension way.

>>> [(index, item) for index, item in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
Or.
>>> [pair for pair in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]

A little different ...

names = ['Google', 'Apple', 'Microsoft']

print(["%d %s" % pair for pair in enumerate(names)])

'''
['0 Google', '1 Apple', '2 Microsoft']
'''

I was trying to get output like this one

0 Google
1 Apple
2 Microsoft

using the list compression...

Some ways,but it can get ugly.
Code in my first post may be the way to go if you want that output.

Vegaseat way is't ok to use '\n'join() method.

>>> print '\n'.join(["%d %s" % pair for pair in enumerate(names)])
0 Google
1 Apple
2 Microsoft

Iterate over list comprehension and print result.

>>> lst = [pair for pair in enumerate(names)]
>>> for i in lst:
        print i[0], i[1]

0 Google
1 Apple
2 Microsoft

Not so nice but it work,maybe there is nicer ways to do this?

>>> print '\n'.join([' '.join([str(index), item]) for index, item in enumerate(names)])
0 Google
1 Apple
2 Microsoft

Or.

>>> print '\n'.join([str(pair[0]) + ' ' + pair[1] for pair in enumerate(names)])    
0 Google
1 Apple
2 Microsoft

OK, but you got some unnecessary love affair with the [], maybe because we are discussing about list comprehensions. But you can do with only generator expressions instead feeding the join method.

Instead of

print '\n'.join(["%d %s" % pair for pair in enumerate(names)])

You can use

print '\n'.join("%d %s" % pair for pair in enumerate(names))

If you want a formatted result string, you can just build one up ...

def show_names(names):
    s = ""
    for ix, name in enumerate(names):
        s += "{} {}\n".format(ix, name)
    return s


names = ['Google', 'Apple', 'Microsoft']
print(show_names(names))

'''
0 Google
1 Apple
2 Microsoft
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.