28

I have tuple in Python that looks like this:

tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', '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 = "http://facebook.com/sparkbrowser"
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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
dzordz
  • 2,277
  • 13
  • 51
  • 74
  • 1
    it's called [*sequence unpacking*](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) (see last paragraph) or just *unpacking*. – n611x007 Jul 08 '15 at 11:00

4 Answers4

51

Python can unpack sequences naturally.

domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
15

Best not to use tuple as a variable name.

You might use split(',') if you had a string like 'sparkbrowser.com,0,http://facebook.com/sparkbrowser,Facebook', 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, 'http://facebook.com/sparkbrowser', '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, 'http://facebook.com/sparkbrowser']

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
5
>>> domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
>>> domain
'sparkbrowser.com'
>>> level
0
>>> url
'http://facebook.com/sparkbrowser'
>>> text
'Facebook'
Joyfulgrind
  • 2,762
  • 8
  • 34
  • 41
1

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, 'http://facebook.com/sparkbrowser', 'Facebook')
>>> site2 = Website('foo.com', 4, 'http://bar.com/sparkbrowser', 'Bar')
>>> site1
Website(domain='sparkbrowser.com', level=0, url='http://facebook.com/sparkbrowser', text='Facebook')
>>> site2
Website(domain='foo.com', level=4, url='http://bar.com/sparkbrowser', text='Bar')
>>> site1.domain
'sparkbrowser.com'
>>> site1.url
'http://facebook.com/sparkbrowser'
>>> site2.level
4
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40