Jason Wells
Jason Wells

Reputation: 21

Printing from a list in Python?

I am working with Python 3.2 and I have a list where the elements may vary in number depending on the original input. How can I print the elements from the list, but add 'and' before the last element when I don't know the exact number of elements in the list?

Upvotes: 2

Views: 129

Answers (3)

Mark
Mark

Reputation: 19969

For a list called floep

print('%s and %s' % (', '.join(floep[:-1]), floep[-1]))

As commented, a mapping might be needed for non-strings

print('%s and %s' % (', '.join(str(x) for x in floep[:-1]), floep[-1]))

Upvotes: 3

Cameron Sparr
Cameron Sparr

Reputation: 3981

for a list, a

a = map(str, a)
print(', '.join(a[:-1]) + ', and ' + a[-1])

edit: I believe IamAlexAlright was right about needing a map first

Upvotes: 2

Bobb Dizzles
Bobb Dizzles

Reputation: 539

Try this:

for i in range(len(list)):
    if i=len(list)-2:
        print('and')
    print(len[i])

Upvotes: 0

Related Questions