<< Back to PYTHON
Python Tuple Examples
Store separate values together with tuples. Pack, unpack and benchmark tuples.Tuple. Consider this starfish. It has 5 arms. It is underwater. These attributes form a unit of information—they could be stored together in a tuple.
Python tuples are values—they never change. Suppose an element has a shape and a color. This forms a tuple pair. Logically this information is a single unit.
Create. A tuple is immutable—this is important to consider. It cannot be changed after created. So the creation syntax must be used often. We use "(" and ")" to create tuples.
Zero elements: To create a tuple with zero elements, use only the two parentheses "()".
One element: For a tuple with one element, use a trailing comma. This helps Python tell that you don't mean an expression, such as (1 + 2).
Two elements: For a tuple with 2 or more elements, use a comma between elements. No ending comma is needed.
Python program that creates tuples
# Zero-element tuple.
a = ()
# One-element tuple.
b = ("one",)
# Two-element tuple.
c = ("one", "two")
print(a)
print(len(a))
print(b)
print(len(b))
print(c)
print(len(c))
Output
()
0
('one',)
1
('one', 'two')
2
Immutable. An immutable object cannot be changed. Once created it always has the same values. A tuple is immutable. Here we attempt to assign the first element in the tuple.
But: This is invalid. When executed, the Python runtime will report a TypeError.
ErrorCreate: To make a new, changed tuple, we would need to create a new tuple. We could specify that some items have the same values.
Info: Immutability seems inefficient. But with it, we can reuse cached (or preexisting) objects more readily.
Python program that assigns tuple
tuple = ('cat', 'dog', 'mouse')
# This causes an error.
tuple[0] = 'feline'
Output
TypeError: 'tuple' object does not support item assignment
Pack, unpack. Tuples can be packed and unpacked. In packing, we place values into a new tuple. And in unpacking we extract those values back into variables.
Note: This syntax form creates elegant and small programs. In this program we pack two strings into a tuple.
Then: We initialize two variables to those two packed values. The variables act like any other variable.
Python program that assigns variables
# Create packed tuple.
pair = ("dog", "cat")
# Unpack tuple.
(key, value) = pair
# Display unpacked variables.
print(key)
print(value)
Output
dog
cat
No parentheses. Tuples are typically specified with surrounding parentheses chars. But suppose you are a wild one. You can just use a comma. The tuple is inferred.
Python program that uses tuples, no parentheses
# A trailing comma indicates a tuple.
one_item = "cat",
# A tuple can be specified with no parentheses.
two_items = "cat", "dog"
print(one_item)
print(two_items)
Output
('cat',)
('cat', 'dog')
Add, multiply. A tuple is not a number. But it can be added to or multiplied. By adding two tuples, they are concatenated. One is put after the other.
And: By multiplying a tuple with a number, we add the tuple to itself a certain number of times.
Warning: This syntax form can become somewhat confusing. I have not used it often on tuples.
Python program that adds and multiples tuples
checks = (10, 20, 30)
# Add two tuples.
more = checks + checks
print(more)
# Multiply tuple.
total = checks * 3
print(total)
Output
(10, 20, 30, 10, 20, 30)
(10, 20, 30, 10, 20, 30, 10, 20, 30)
Max, min. The max and min functions can be used on tuples. These functions locate the item that would be sorted last (max) or sorted first (min).
Max, minFor strings: The comparison performed is alphabetical—"able" comes before "zero". So "able" would be less than "zero".
For numbers: The comparison is numeric—10 comes before 20. These comparisons are logical.
Python program that uses max and min
# Max and min for strings.
friends = ("sandy", "michael", "aaron", "stacy")
print(max(friends))
print(min(friends))
# Max and min for numbers.
earnings = (1000, 2000, 500, 4000)
print(max(earnings))
print(min(earnings))
Output
stacy
aaron
4000
500
In keyword. This example creates a two-element tuple (a pair). It searches the tuple for the string "cat". It then searches for "bird", but this string does not exist.
Note: With the in-keyword, we can search a tuple. We use in as part of an if-statement. And we can combine in with not—this is "not in".
InPython program that searches tuples
pair = ("dog", "cat")
# Search for a value.
if "cat" in pair:
print("Cat found")
# Search for a value not present.
if "bird" not in pair:
print("Bird not found")
Output
Cat found
Bird not found
Slice. A tuple can be sliced. The slice notation uses a colon. On the left side of the colon, we have the starting index. If no starting index is present, the program uses 0.
SliceAnd: On the right side of the colon, we have the ending index. If no ending index is present, the last index possible is used.
Note: Slicing creates a new tuple. A slice that specifies no indexes is a simple way to copy a tuple.
Python program that uses tuple slices
values = (1, 3, 5, 7, 9, 11, 13)
# Copy the tuple.
print(values[:])
# Copy all values at index 1 or more.
print(values[1:])
# Copy one value, starting at first.
print(values[:1])
# Copy values from index 2 to 4.
print(values[2:4])
Output
(1, 3, 5, 7, 9, 11, 13)
(3, 5, 7, 9, 11, 13)
(1,)
(5, 7)
Index. This gets the index of an element. Here we search for the value "dog," and get the index 1 (the second position). If we use index() on a value that is not found, an error results.
Tip: Consider the in operator before calling index() on a value that might not exist. This prevents a possible exception.
Python program that uses index
# Three-item tuple.
items = ("cat", "dog", "bird")
# Get index of element with value "dog".
index = items.index("dog")
print(index, items[index])
Output
1 dog
Count. This returns the number of elements with a specific value in a tuple. If you need to get the total length of the tuple, please use len. Count only counts certain values.
Python program that uses count
values = (1, 2, 2, 3, 3, 3)
print(values.count(1))
print(values.count(3))
# There are no 100 values, so this returns 0.
print(values.count(100))
Output
1
3
0
Keys, dictionary. We next use a tuple as a dictionary key. Dictionaries can use tuple keys without worrying about them changing. Here we use the pair of values 1 and 2 to look up a value.
Tip: You can use tuples in this way to create a two-dimensional dictionary. Use a tuple to represent X and Y coordinates.
Python program that uses tuples as dictionary keys
# A tuple with two numbers.
pair = (1, 2)
# Create a dictionary.
# ... Use the tuple as a key.
dict = {}
dict[pair] = "Python"
# Access the dictionary using a tuple.
print(dict[(1, 2)])
Output
Python
Convert. A tuple cannot be modified. But a list can be changed in many ways. For this reason we often need to convert a tuple into a list.
List: The list built-in accepts a tuple as its argument. Here we use sort() on the resulting list.
Finally: In the program, we convert the list back into a tuple. This is done with the tuple() function.
Here: We see that a list has square brackets. A tuple has round ones. This is an important part of Python's syntax.
Python program that converts tuple and list
# Tuple containing unsorted odd numbers.
odds = (9, 5, 11)
# Convert to list and sort.
list = list(odds)
list.sort()
print(list)
# Convert back to tuple.
sorted_odds = tuple(list)
print(sorted_odds)
Output
[5, 9, 11]
(5, 9, 11)
Enumerate. This is a built-in method. Enumerate() returns a tuple of an index and the element value at that index. It is often used on a list.
Here: We use enumerate on a list of strings. We can access the tuple, or directly unpack the tuple in the for-statement.
Python program that uses enumerate
values = ["meow", "bark", "chirp"]
# Use enumerate on list.
for pair in enumerate(values):
# The pair is a 2-tuple.
print(pair)
# Unpack enumerate's results in for-loop.
for index, value in enumerate(values):
# We have already unpacked the tuple.
print(str(index) + "..." + value)
Output
(0, 'meow')
(1, 'bark')
(2, 'chirp')
0...meow
1...bark
2...chirp
List of tuples. Let us examine a practical example. This program divides a string into a list of tuples. Each tuple has adjacent characters from the string.
Range: We use the range built-in to iterate over the string, with a step of 2. We start at index 1 to avoid the first char.
Append: We call append() on the list (called "pairs") and as the argument to append, we create a two-element tuple (a pair).
Python program that uses list of tuples
value = "abcdefgh"
pairs = []
# Loop over string.
# ... Use step of 2 in range built-in.
# ... Extract pairs of letters into a list of tuples.
for i in range(1, len(value), 2):
one = value[i - 1]
two = value[i]
pairs.append((one, two))
# Display list of tuple pairs.
for pair in pairs:
print(pair)
Output
('a', 'b')
('c', 'd')
('e', 'f')
('g', 'h')
Swap. To flip or swap variables, we do not need a temporary variable. We can use a tuple unpacking expression. We assign each variable to the other one in a single statement.
Python program that flips variables
left = "cat"
right = "dog"
print("LEFT", left)
print("RIGHT", right)
print(":::FLIP:::")
# Use tuple unpacking to flip variables.
left, right = right, left
print("LEFT", left)
print("RIGHT", right)
Output
LEFT cat
RIGHT dog
:::FLIP:::
LEFT dog
RIGHT cat
Benchmark. How do we choose between the syntax forms for tuples? In this benchmark we test two ways of assigning variables to values in a tuple. We unpack tuples.
Version 1: This version of the program uses a single statement to unpack an existing tuple.
Version 2: This version assigns to the elements in a tuple using the "[" and "]" syntax.
Result: Version 1, which unpacks the tuple in a single statement, is somewhat faster.
Note: In Python, the number of statements often influences greatly the results. This may change as more advanced compilers appear.
Python program that benchmarks tuple
import time
pair = (1, 2)
print(time.time())
# Version 1: unpack tuple.
i = 0
while i < 10000000:
(a, b) = pair
i = i + 1
print(time.time())
# Version 2: assign variables to tuple separately.
i = 0
while i < 10000000:
a = pair[0]
b = pair[1]
i = i + 1
print(time.time())
Output
1345673733.21
1345673737.12 (Unpack: 3.91 s)
1345673742.12 (Assign: 5.00 s)
Divide, subtract. We cannot divide or subtract tuples. Out of curiosity I tried this. I received the TypeError with "unsupported operand type."
Operand: As a reminder, an operand is a value on one side of an expression. It is part of an operation.
Research. A tuple is a sequence, much like a list (and not like a class). In the Python documentation, we find that the enumerate() built-in returns tuples.
Quote: Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in).
Built-in Types: python.org
Namedtuple. In normal tuples, fields have no names. With namedtuple, a type from the collections module, we can provide names to a tuple's fields.
NamedtupleWith tuples, we have access to many (but not all) of the methods of a list. Tuples are key to other important types, such as dictionary. And they are used, to some advantage, within lists.
Usage. Tuples are often combined with other types. Often we store tuples within lists to create a list of pairs. In this way we avoid combining values together in strings.
Related Links:
- Python global and nonlocal
- Python not: If Not True
- Python Convert Decimal Binary Octal and Hexadecimal
- Python Tkinter Scale
- Python Tkinter Scrollbar
- Python Tkinter Text
- Python History
- Python Number: random, float and divmod
- Python Tkinter Toplevel
- Python Tkinter Spinbox
- Python Tkinter PanedWindow
- Python Tkinter LabelFrame
- Python Tkinter MessageBox
- Python Website Blocker
- Python Console Programs: Input and Print
- Python Display Calendar
- Python Check Number Odd or Even
- Python readline Example: Read Next Line
- Python Anagram Find Method
- Python Any: Any Versus All, List Performance
- Python Filename With Date Example (date.today)
- Python Find String: index and count
- Python filter (Lambda Removes From List or Range)
- Python ASCII Value of Character
- Python Sum Example
- Python make simple Calculator
- Python Add Two Matrices
- Python Multiply Two Matrices
- Python SyntaxError (invalid syntax)
- Python Transpose Matrix
- Python Remove Punctuation from String
- Python Dictionary items() method with Examples
- Python Dictionary keys() method with Examples
- Python Textwrap Wrap Example
- Python Dictionary popitem() method with Examples
- Python Dictionary pop() method with Examples
- Python HTML: HTMLParser, Read Markup
- Python Tkinter Tutorial
- Python Array Examples
- Python ord, chr Built Ins
- Python Dictionary setdefault() method with Examples
- Python Dictionary update() method with Examples
- Python Dictionary values() method with Examples
- Python complex() function with Examples
- Python delattr() function with Examples
- Python dir() function with Examples
- Python divmod() function with Examples
- Python Loops
- Python for loop
- Python while loop
- Python enumerate() function with Examples
- Python break
- Python continue
- Python dict() function with Examples
- Python pass
- Python Strings
- Python Lists
- Python Tuples
- Python Sets
- Python Built-in Functions
- Python filter() function with Examples
- Python dict Keyword (Copy Dictionary)
- Python Dictionary Order Benchmark
- Python Dictionary String Key Performance
- Python 2D Array: Create 2D Array of Integers
- Python Divmod Examples, Modulo Operator
- bin() in Python | Python bin() Function with Examples
- Python Oops Concept
- Python Object Classes
- Python Constructors
- Python hash() function with Examples
- Python Pandas | Python Pandas Tutorial
- Python Class Examples: Init and Self
- Python help() function with Examples
- Python IndentationError (unexpected indent)
- Python Index and Count (Search List)
- Python min() function with Examples
- Python classmethod and staticmethod Use
- Python set() function with Examples
- Python hex() function with Examples
- Python id() function with Examples
- Python sorted() function with Examples
- Python next() function with Examples
- Python Compound Interest
- Python List insert() method with Examples
- Python Datetime Methods: Date, Timedelta
- Python setattr() function with Examples
- Python 2D List Examples
- Python Pandas Data operations
- Python Def Methods and Arguments (callable)
- Python slice() function with Examples
- Python Remove HTML Tags
- Python input() function with Examples
- Python enumerate (For Index, Element)
- Python Display the multiplication Table
- Python int() function with Examples
- Python Error: Try, Except and Raise
- Python isinstance() function with Examples
- Python oct() function with Examples
- Python startswith, endswith Examples
- Python List append() method with Examples
- Python NumPy Examples (array, random, arange)
- Python Replace Example
- Python List clear() method with Examples
- Python List copy() method with Examples
- Python Lower Dictionary: String Performance
- Python Lower and Upper: Capitalize String
- Python Dictionary Examples
- Python map Examples
- Python Len (String Length)
- Python Padding Examples: ljust, rjust
- Python Type: setattr and getattr Examples
- Python String List Examples
- Python String
- Python Remove Duplicates From List
- Python If Examples: Elif, Else
- Python Programs | Python Programming Examples
- Python List count() method with Examples
- Python List extend() method with Examples
- Python List index() method with Examples
- Python List pop() method with Examples
- Python Palindrome Method: Detect Words, Sentences
- Python Path: os.path Examples
- Python List remove() method with Examples
- Python List reverse() method with Examples
- Top 50+ Python Interview Questions (2021)
- Python List sort() method with Examples
- Python sort word in Alphabetic Order
- abs() in Python | Python abs() Function with Examples
- Python String | encode() method with Examples
- all() in Python | Python all() Function with Examples
- any() in Python | Python any() Function with Examples
- Python Built In Functions
- ascii() in Python | Python ascii() Function with Examples
- Python bytes, bytearray Examples (memoryview)
- bool() in Python | Python bool() Function with Examples
- bytearray() in Python | Python bytearray() Function with Examples
- Python Caesar Cipher
- bytes() in Python | Python bytes() Function with Examples
- Python Sum of Natural Numbers
- callable() in Python | Python callable() Function with Examples
- Python Set add() method with Examples
- Python Set discard() method with Examples
- Python Set pop() method with Examples
- Python math.floor, import math Examples
- Python Return Keyword (Return Multiple Values)
- Python while Loop Examples
- Python Math Examples
- Python Reverse String
- Python max, min Examples
- Python pass Statement
- Python Set remove() method with Examples
- Python Dictionary
- Python Functions
- Python String | capitalize() method with Examples
- Python String | casefold() method with Examples
- Python re.sub, subn Methods
- Python subprocess Examples: subprocess.run
- Python Tkinter Checkbutton
- Python Tkinter Entry
- Python String | center() method with Examples
- Python Substring Examples
- Python pow Example, Power Operator
- Python Lambda
- Python Files I/O
- Python Modules
- Python String | count() method with Examples
- Python String | endswith() method with Examples
- Python String | expandtabs() method with Examples
- Python Prime Number Method
- Python String | find() method with Examples
- Python String | format() method with Examples
- Python String | index() method with Examples
- Python String | isalnum() method with Examples
- Python String | isalpha() method with Examples
- Python String | isdecimal() method with Examples
- Python Pandas Sorting
- Python String | isdigit() method with Examples
- Python Convert Types
- Python String | isidentifier() method with Examples
- Python Pandas Add column to DataFrame columns
- Python String | islower() method with Examples
- Python Pandas Reading Files
- Python Right String Part
- Python IOError Fix, os.path.exists
- Python Punctuation and Whitespace (string.punctuation)
- Python isalnum: String Is Alphanumeric
- Python Pandas Series
- Python Pandas DataFrame
- Python Recursion Example
- Python ROT13 Method
- Python StringIO Examples and Benchmark
- Python Import Syntax Examples: Modules, NameError
- Python in Keyword
- Python iter Example: next
- Python Round Up and Down (Math Round)
- Python List Comprehension
- Python Collection Module
- Python Math Module
- Python OS Module
- Python Random Module
- Python Statistics Module
- Python String Equals: casefold
- Python Sys Module
- Top 10 Python IDEs | Python IDEs
- Python Arrays
- Python Magic Method
- Python Stack and Queue
- Python MySQL Environment Setup
- Python MySQL Database Connection
- Python MySQL Creating New Database
- Python MySQL Creating Tables
- Python Word Count Method (re.findall)
- Python String Literal: F, R Strings
- Python MySQL Update Operation
- Python MySQL Join Operation
- Python Armstrong Number
- Learn Python Tutorial
- Python Factorial Number using Recursion
- Python Features
- Python Comments
- Python if else
- Python Translate and Maketrans Examples
- Python Website Blocker | Building Python Script
- Python Itertools Module: Cycle and Repeat
- Python Operators
- Python Int Example
- Python join Example: Combine Strings From List
- Python Read CSV File
- Python Write CSV File
- Python Read Excel File
- Python Write Excel File
- Python json: Import JSON, load and dumps
- Python Lambda Expressions
- Python Print the Fibonacci sequence
- Python format Example (Format Literal)
- Python Namedtuple Example
- Python SciPy Tutorial
- Python Applications
- Python KeyError Fix: Use Dictionary get
- Python Resize List: Slice and Append
- Python String | translate() method with Examples
- Python Copy List (Slice Entire List)
- Python None: TypeError, NoneType Has No Length
- Python MySQL Performing Transactions
- Python String | isnumeric() method with Examples
- Python MongoDB Example
- Python String | isprintable() method with Examples
- Python Tkinter Canvas
- Python String | isspace() method with Examples
- Python Tkinter Frame
- Python Tkinter Label
- Python Tkinter Listbox
- Python String | istitle() method with Examples
- Python Website Blocker | Script Deployment on Linux
- Python Website Blocker | Script Deployment on Windows
- Python String | isupper() method with Examples
- Python String split() method with Examples
- Python Slice Examples: Start, Stop and Step
- Python String | join() method with Examples
- Python String | ljust() method with Examples
- Python Sort by File Size
- Python Arithmetic Operations
- Python String | lower() method with Examples
- Python Exception Handling | Python try except
- Python Date
- Python Regex | Regular Expression
- Python Sending Email using SMTP
- Python Command Line Arguments
- Python List Comprehension Examples
- Python Assert Keyword
- Python Set Examples
- Python Fibonacci Sequence
- Python Maze Pathfinding Example
- Python Memoize: Dictionary, functools.lru_cache
- Python Timeit, Repeat Examples
- Python Strip Examples
- Python asyncio Example: yield from asyncio.sleep
- Python String Between, Before and After Methods
- Python bool Use (Returns True or False)
- Python Counter Example
- Python frozenset: Immutable Sets
- Python Generator Examples: Yield, Expressions
- Python CSV: csv.reader and Sniffer
- Python globals, locals, vars and dir
- Python abs: Absolute Value
- Python gzip: Compression Examples
- Python Function Display Calendar
- Python Display Fibonacci Sequence Recursion
- Python String | lstrip() method with Examples
- Python del Operator (Remove at Index or Key)
- Python String | partition() method with Examples
- Python String | replace() method with Examples
- Python Zip Examples: Zip Objects
- Python String | rfind() method with Examples
- Python String | rindex() method with Examples
- Python String rjust() method with Examples
- Python String rpartition() method with Examples
- Python String rsplit() method with Examples
- Python Area Of Triangle
- Python Quadratic Equation
- Python swap two Variables
- Python Generate Random Number
- Python Convert Kilometers to Miles
- Python Convert Celsius to Fahrenheit
- Python Check Number Positive Negative or Zero
- Python Check Leap Year
- Python Check Prime Number
- Top 40 Python Pandas Interview Questions (2021)
- Python Check Armstrong Number
- Python SQLite Example
- Python Tkinter Button
- Python Find LCM
- Python Find HCF
- Python Tuple Examples
- Python String | rstrip() method with Examples
- Python String splitlines() method with Examples
- Python String | startswith() method with Examples
- Python String | swapcase() method with Examples
- Python Truncate String
- Python String | upper() method with Examples
- Python for: Loop Over String Characters
- Python String | zfill() method with Examples
- Python Sort Examples: Sorted List, Dictionary
- Python XML: Expat, StartElementHandler
- Python Urllib Usage: Urlopen, UrlParse
- Python File Handling (with open, write)
- Python Example
- Python variables
- Python Random Numbers: randint, random.choice
- Python assert, O Option
- Python Data Types
- Python keywords
- Python literals
- Python MySQL Insert Operation
- Python MySQL Read Operation
- Python ascii Example
- Python ASCII Table Generator: chr
- Python Range: For Loop, Create List From Range
- Python re.match Performance
- Python re.match, search Examples
- Python Tkinter Menubutton
- Python Tkinter Menu
- Python Tkinter Message
- Python Tkinter Radiobutton
- Python List Examples
- Python Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf