Split Tuple Items to Separate Variables

Split Tuple Items to Separate Variables

I have tuple in Python that looks like this:

tuple = ('sparkbrowser.com', 0, ' 'Facebook')

and I wanna split it out so I could get every item from tuple independent so I could do something like this:

domain = "sparkbrowser.com"
level = 0
url = ""
text = "Facebook"

or something similar to that, My need is to have every item separated. I tried with .split(",") on tuple but I've gotten error which says that tuple doesn't have split option.

1

4 Answers

Python can unpack sequences naturally.

domain, level, url, text = ('sparkbrowser.com', 0, ' 'Facebook')
1

Best not to use tuple as a variable name.

You might use split(',') if you had a string like 'sparkbrowser.com,0,, that you needed to convert to a list. However you already have a tuple, so there is no need here.

If you know you have exactly the right number of components, you can unpack it directly

the_tuple = ('sparkbrowser.com', 0, ' 'Facebook')
domain, level, url, text = the_tuple

Python3 has powerful unpacking syntax. To get just the domain and the text you could use

domain, *rest, text = the_tuple

rest will contain [0, '

>>> domain, level, url, text = ('sparkbrowser.com', 0, ' 'Facebook')
>>> domain
'sparkbrowser.com'
>>> level
0
>>> url
'
>>> text
'Facebook'

An alternative for this, is to use collections.namedtuple. It makes accessing the elements of tuples easier.

Demo:

>>> from collections import namedtuple
>>> Website = namedtuple('Website', 'domain level url text')
>>> site1 = Website('sparkbrowser.com', 0, ' 'Facebook')
>>> site2 = Website('foo.com', 4, ' 'Bar')
>>> site1
Website(domain='sparkbrowser.com', level=0, url=' text='Facebook')
>>> site2
Website(domain='foo.com', level=4, url=' text='Bar')
>>> site1.domain
'sparkbrowser.com'
>>> site1.url
'
>>> site2.level
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.