Suppose I have a list:
a=[1,2,3,4,5]
Now I want to convert this list into a tuple. I thought coding something like this would do:
state=() for i in a: state=state+i
and it gave an error. It's quite obvious why, I am trying to concatenate an integer with a tuple.
But tuples don't have the same functions as lists do, like insert or append. So how can I add elements through looping? Same thing with dictionaries, I feel as if I have a missing link.
When it is required to concatenate multiple tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements.
You can use + operator to concatenate two or more tuples.
You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples. You can only add or combine same data types. Thus combining a tuple and a list gives you an error.
join() The join() method is a string method and returns a string in which the elements of the sequence have been joined by a str separator. Using join() we add the characters of the tuple and convert it into a string.
Tuples are immutable, you cannot append, delete, or edit them at all. If you want to turn a list into a tuple, you can just use the tuple function:
tuple(a)
If, for some reason, you feel the need to append to a tuple (You should never do this), you can always turn it back into a list, append, then turn it back into a tuple:
tuple(list(a)+b)
Keep getting votes for this, which means people keep seeing it, so time to update and remove misinformation.
It's OK to add elements to a tuple (sort of). That was a silly thing to say. Tuples are still immutable, you can't edit them, but you can make new ones that look like you appended by putting multiple tuples together. tuple(list(a)+b)
is stupid, don't do that. Just do tuple1 + tuple2
, because Python doesn't suck. For the provided code, you would want:
state = () for i in a: state += (i,)
The Paul's response to this answer is way more right than this answer ever was.
Now I can stop feeling bad about this.
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