Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating Tuple

Tags:

python

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.

like image 205
user784530 Avatar asked May 05 '12 06:05

user784530


People also ask

How do you concatenate to a tuple?

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.

How can we concatenate two tuples in Python?

You can use + operator to concatenate two or more tuples.

Can you combine 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.

How do I concatenate a tuple to a string?

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.


1 Answers

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.

like image 50
Josiah Avatar answered Sep 20 '22 08:09

Josiah