e = ('ham', 5, 1, 'bird')
logfile.write(','.join(e))
I have to join it so that I can write it into a text file.
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.
That's right: Adding a list to a tuple with + doesn't work. But if we use +=, it does.
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.
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'
join()
only works with strings, not with integers. Use ','.join(str(i) for i in e)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With