Split tuple items to separate variables

113,766

Solution 1

Python can unpack sequences naturally.

domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')

Solution 2

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']

Solution 3

>>> domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
>>> domain
'sparkbrowser.com'
>>> level
0
>>> url
'http://facebook.com/sparkbrowser'
>>> text
'Facebook'

Solution 4

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
Share:
113,766

Related videos on Youtube

dzordz
Author by

dzordz

Updated on December 31, 2020

Comments

  • dzordz
    dzordz over 3 years

    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.

    • n611x007
      n611x007 almost 9 years
      it's called sequence unpacking (see last paragraph) or just unpacking.
  • Noumenon
    Noumenon about 5 years
    I want to note this works for a list of tuples as well: for a, b in [(a1, b1), (a2, b2)].