2

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?

1
  • So [1, 2, 3, 4, 5] is 1, 2, 3, 4 and 5 ? Commented Dec 7, 2012 at 1:04

3 Answers 3

3

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]))
Sign up to request clarification or add additional context in comments.

4 Comments

I'm not familiar with python 3.2 so I could be totally off base though but will ''.join work on a list of ints? I have to map(str,list) before I can join in python2.7
Saying map(lambda x: str(x), ... when you can say map(str, ... looks kind of silly.
Okay how's this? [str(x) for x in floep[:-1]] Prettier?
I would use a generator expression like this: ','.join(str(x) for x in floep[:-1]).
2

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

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.