4
Contributors
8
Replies
49
Views
4 Years
Discussion Span
Last Post by vegaseat
Featured Replies
  • 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')] Read More

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

0 Google
1 Apple
2 Microsoft
0

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

1

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

A little different ...

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

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

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

I was trying to get output like this one

0 Google
1 Apple
2 Microsoft

using the list compression...

0

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

Edited by snippsat

0

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))
0

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
'''
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.