Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I join this tuple in Python?

Tags:

python

tuples

e = ('ham', 5, 1, 'bird')
logfile.write(','.join(e))

I have to join it so that I can write it into a text file.

like image 234
TIMEX Avatar asked Nov 29 '09 11:11

TIMEX


People also ask

Can you join a tuple in Python?

The join function can be used to join each tuple elements with each other and list comprehension handles the task of iterating through the tuples.

Can you use += for tuples?

That's right: Adding a list to a tuple with + doesn't work. But if we use +=, it does.

What can you do with a list that you can't with a tuple?

Lists are mutable while tuples are immutable, and this marks the key difference between the two. What does this mean? We can change/modify the values of a list but we cannot change/modify the values of a tuple. Since lists are mutable, we can't use a list as a key in a dictionary.


2 Answers

join only takes lists of strings, so convert them first

>>> e = ('ham', 5, 1, 'bird') >>> ','.join(map(str,e)) 'ham,5,1,bird' 

Or maybe more pythonic

>>> ','.join(str(i) for i in e) 'ham,5,1,bird' 
like image 156
Nick Craig-Wood Avatar answered Sep 24 '22 02:09

Nick Craig-Wood


join() only works with strings, not with integers. Use ','.join(str(i) for i in e).

like image 43
djc Avatar answered Sep 22 '22 02:09

djc