Problem Formulation and Solution Overview
💡 Definition: Python Tuples are a type of Data Structure similar to Lists. However, Tuples are enclosed in round brackets
() and are immutable, whereas Lists are enclosed in square brackets
 and are mutable. Another point worth mentioning is that Tuples tend to be more memory-efficient than Lists.
To make it more fun, we have the following running scenario:
ncic_codes = [(101, 'Treason'), (102, 'Treason Misprision'), (103, 'Espionage'), (104, 'Sabotage'), (105, 'Sedition'), (106, 'Selective Service'), (199, 'Sovereignty-Remarks'), (201, 'Military Desertion'), (299, 'Military-Remarks'), (301, 'Illegal Entry')]
Method 1: Use index to access Specific Tuple Element
code_103 = ncic_codes print(code_103)
However, we need to append
ncic_codes) to retrieve the Offence Description. The results save to
code_103 and output to the terminal.
Method 2: Use List Comprehension to Access all Tuple Elements
all_tuples = [x for x in ncic_codes] print(all_tuples)
Method 3: Use List Comprehension to Search a List of Tuples
search_res = [x for x in ncic_codes if x >= 200] print(search_res)
List Comprehension to search for and return
Tuples from a List of Tuples where the Offense Code is greater than or equal to (
>=) 200. The results save to
search_res and are output to the terminal.
|[201, 299, 301]|
Method 4: Use Unpacking
n_codes = (101, 102, 103, 104, 105) code_101, *_ = n_codes print(n_codes)
Above declares a
Tuple containing the first five (5) Offense Codes from the National Crime Information Center and saves them to
The following line references the first
*_ is called. This is the
unpacking symbol and indicates to Python to retrieve (unpack) the remainder of the
Tuple elements. These results are then output to the terminal.
|(101, 102, 103, 104, 105)|
Method 5: Use Slicing
sliced = ncic_codes[3:6] print(sliced)
The results save to
sliced and are output to the terminal as a sliced List of Tuples.
The Tuples below in bold indicate the extracted data using the above slicing range.
Method 6: Use filter and a Lambda
ncic_filter = list(filter(lambda x: x == 199, ncic_codes)) print(ncic_filter)
Above calls the
filter() method and passes a
lambda as an argument. This loops through
ncic_codes and returns Tuples where the first element of the Tuple (the Offense Code) equals 199. The results are converted to a List format, saved to
ncic_filter and output to the terminal.
Programmer Humor – Blockchain
At university, I found my love of writing and coding. Both of which I was able to use in my career.
During the past 15 years, I have held a number of positions such as:
In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM
Corporate Trainer (staff of 30+)
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder