How do you split a tuple object in python?

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


Here is a tuple with 12 integers. In order to split it in four sub-tuple of three elements each, slice a tuple of three successive elements from it and append the segment in a lis. The result will be a list of 4 tuples each with 3 numbers.

>>> tup=(7,6,8,19,2,4,13,1,10,25,11,34)
>>> lst=[]
>>> for i in range(0,10,3):
lst.append((tup[i:i+3]))
>>> lst
[(7, 6, 8), (19, 2, 4), (13, 1, 10), (25, 11, 34)]

How do you split a tuple object in python?

Updated on 17-Jun-2020 10:15:55

  • Related Questions & Answers
  • How to Concatenate tuples to nested tuples in Python
  • Convert list of tuples into digits in Python
  • Convert list of tuples into list in Python
  • Combining tuples in list of tuples in Python
  • Count tuples occurrence in list of tuples in Python
  • Remove duplicate tuples from list of tuples in Python
  • Python program to convert a list of tuples into Dictionary
  • Updating Tuples in Python
  • Compare tuples in Python
  • Python program to find Tuples with positive elements in List of tuples
  • Chunk Tuples to N in Python
  • Ways to concatenate tuples in Python
  • Python program to construct Equidigit tuples
  • Python program to find Tuples with positive elements in a List of tuples
  • Python - Column summation of tuples

Python Beginner Concepts Tutorial

  • April 1, 2018
  • Key Terms: tuples

A tuple is a sequence of values. The values can be of any type.

A major difference between tuples and other data structures is that tuples are immutable. Because tuples are immutable, you can't modify elements inside of a tuple.

This immutability could be helpful if you're writing a program and want to store data that shouldn't be changed. Possible examples include:

  • credit card information
  • birthdate
  • birth name

How to create a tuple¶

Tuples are comma-separated values. It is common to enclose tuples in parentheses.

To create a tuple with a single element, you have to include a final comma.

We can verify this data structure is a tuple by passing it into the type() function.

Retrieve a tuple element via indexing¶

Similar to lists, tuples can be indexed by integers using the bracket operator.

We can retrieve the number 3 in our values tuple at index position of 2.

Tuple assignment¶

In Python, you can call the split() method on a string and pass in an argument to split the string on.

We can split the string below, my email address, in half on the @ symbol since there is just one in the string.

This operation returns a list.

In [65]:

''.split('@')

We can also assign username and domain, comma-separated tuple elements, to be the result of the two elements after the split operation.

In doing this, the number of variables on the left and the number of variables on the right side of our expression have to be the same. In this case, it's 2.

In [66]:

username, domain = ''.split('@')

The right side of this assignment returned a list. However, in Python, for tuple assignments, it could work with any kind of sequence such as a string, list or tuple.

Tuples as return values of functions¶

A function can only return one value. However, that one value could be a tuple - similar to the effect of returning multiple values.

For example, we can use a built-in Python function called divmod to compute the quotient and remainder at the same time.

math
9/2 = 4.5

However, you can also express that result as a quotient of 4 with a remainder of 1.

We can store this result as a tuple.

In [70]:

tuple_result = divmod(9, 2)

Or we can use tuple assignment to store the elements separately as variables.

In [72]:

quotient, remainder = divmod(9, 2)

We can also write our own function that returns a tuple of two elements.

In [75]:

def calculate_quotient_and_remainder(dividend, divisor):
    """
    Given two numbers, calculate the quotient and remainder 

    :param dividend: a number meant to be the numerator of our equation
    :param divisor: a number meant to be the denominator of our equation
    :returns: quotient, remainder: a tuple of our (quotient, remainder) 
    """
    quotient = dividend // divisor
    remainder = dividend % divisor
    return quotient, remainder

In [76]:

calculate_quotient_and_remainder(9, 2)

Tuples and dictionaries¶

items method for dictionaries¶

Tuples can be useful as dictionary keys too since they can hold multiple values.

You cannot use a Python list for a dictionary key.

Let's say you had a record of friends and their phone numbers in a program stored as a dictionary.

In [77]:

friends = {"Eric Friedman": 5555555555, "Dan Friedman": 5551231234}

Dictionaries have a method called items that returns a sequence of tuples, where each tuple is a key-value pair.

Out[78]:

dict_items([('Eric Friedman', 5555555555), ('Dan Friedman', 5551231234)])

This result is a dict_items object, which is an iterator that iterates the key-value pairs.

Sort dictionary keys¶

A common operation you may want to do with a record of contact names and phone numbers is to sort names by either first name or last name.

We can use the Python built-in sorted method to sort our keys alphabetically. Because of our string names, this will default to sort by first names alphabetically.

Out[79]:

[('Dan Friedman', 5551231234), ('Eric Friedman', 5555555555)]

Notice how Dan appears now before Eric and we're returned a new list of tuples.

However, what if we want to sort by last name?

There may be a complex way to do it given our current data structure. However, we could simply represent the keys of our dictionary as (first_name, last_name) - a tuple. This may help us more easily sort by first or last name later on.

In [80]:

new_friends = {("Dan", "Williams"): 5555555555, ("Jamie", "Brown"): 5551231234}

This code below sorts the friends last names alphabetically from A to Z.

We pass a value to the second argument of sorted that's a small anonymous function; this function uses the lambda keyword so we sort by the value at index 1 in each dictionary key - in which index 1 is the last name of each tuple.

In [81]:

sorted(new_friends.items(), key=lambda x: x[1])

Out[81]:

[(('Jamie', 'Brown'), 5551231234), (('Dan', 'Williams'), 5555555555)]

Notice how Brown appears before Williams since b comes before w in the alphabet.

This is just one example of how storing dictionary keys as tuples could be valuable for later data manipulation.

How do you split tuples in Python?

The only way to divide each element in a tuple by a number is to create a new tuple that contains the results of the division. An alternative approach to using a generator expression is to use the map() function.

Does slicing work on tuples?

We can use slicing in tuples I'm the same way as we use in strings and lists. Tuple slicing is basically used to obtain a range of items. Furthermore, we perform tuple slicing using the slicing operator. We can represent the slicing operator in the syntax [start:stop:step].

Does split return a tuple?

The partition function splits the entire string into 3 parts and returns it as a tuple of 3 elements. This function splits only once and it will not split iteratively. So it splits at the first occurance of the separator.

How do you get one part of a tuple?

To get the first element of each tuple in a list: Declare a new variable and set it to an empty list. Use a for loop to iterate over the list of tuples. On each iteration, append the first tuple element to the new list.