Lists, Tuples, Sets, Dictionaries, and Data Structures in Python

  • Lists, tuples, sets, dictionaries, and other data structures are fundamental components of Python programming. They provide different ways to store, organize, access, modify, and analyze information. In bioinformatics, these structures are essential for managing DNA and RNA sequences, protein sequences, gene annotations, genetic variants, gene expression measurements, biological identifiers, and results from computational analyses. Choosing an appropriate data structure can improve program readability, computational efficiency, memory usage, and the reliability of biological data processing.
  • A data structure is a method of organizing data so that it can be accessed and manipulated efficiently. Different structures support different operations. Lists are useful for ordered collections that may change, tuples represent ordered collections that are generally fixed, sets store unique elements, and dictionaries associate keys with values. Other important structures include strings, arrays, stacks, queues, linked lists, trees, graphs, and specialized numerical arrays and data frames provided by scientific Python libraries.
  • Python provides several built-in data structures that are easy to use and can be combined to represent complex biological information. For example, a list can store multiple DNA sequences, a dictionary can associate gene names with expression values, a set can identify unique genes, and a tuple can represent a fixed coordinate pair. Understanding these structures helps bioinformatics programmers design efficient algorithms and build reusable analysis pipelines.
  • A Python list is an ordered, mutable collection of elements. Ordered means that elements maintain their sequence position, while mutable means that elements can be added, removed, or changed after the list is created. Lists can contain strings, numbers, Boolean values, objects, or other collections. They are created using square brackets, and individual elements are accessed through indexing. Python uses zero-based indexing, meaning that the first element has index zero.

dna_sequences = [

    “ATGCGT”,

    “TTAGCA”,

    “GGCATA”

]

print(dna_sequences[0])

print(dna_sequences[1])

print(len(dna_sequences))

  • In this example, the list contains three DNA sequences. The first sequence is retrieved using index zero, and the len() function returns the number of elements. Negative indexing can access elements from the end of a list, while slicing extracts a range of elements. For example, dna_sequences[-1] returns the final sequence, and dna_sequences[0:2] returns a new list containing the first two sequences.
  • Lists support numerous operations, including appending new elements, inserting elements at specific positions, removing elements, sorting, reversing, and combining collections. These operations are useful when reading sequence records, collecting gene identifiers, storing measurements, or building intermediate results during a computational analysis.

genes = [“BRCA1”, “TP53”, “EGFR”]

genes.append(“MYC”)

genes.remove(“EGFR”)

print(genes)

  • Lists can also store nested collections. For example, a list of lists may represent a small gene-expression matrix, with each inner list containing measurements for a particular sample or group of genes. However, ordinary nested lists do not automatically enforce consistent row lengths or provide the optimized numerical operations available in libraries such as NumPy and pandas. For large biological datasets, specialized arrays and data frames are often more suitable.
  • List comprehensions provide a concise way to construct lists from existing collections. They are useful for filtering sequences, transforming measurements, and extracting features from biological records.

sequences = [“ATGC”, “ATGCGC”, “TTAA”, “GGCC”]

long_sequences = [

    sequence for sequence in sequences

    if len(sequence) >= 5

]

print(long_sequences)

  • This example selects sequences containing at least five nucleotides. List comprehensions are convenient for simple transformations and filters, but complex processing is often easier to maintain when written as a separate function or a conventional loop.
  • A tuple is an ordered collection that is generally used when the collection should not be structurally modified. Tuples are commonly created using parentheses, although parentheses are not always required. They support indexing, slicing, iteration, and repeated values, much like lists. Unlike lists, tuples do not support operations such as appending or removing individual elements. A tuple can contain mutable objects, however, so it should not be assumed that every object stored inside a tuple is immutable.

gene_coordinates = (“chr1”, 12500, 13800)

chromosome = gene_coordinates[0]

start_position = gene_coordinates[1]

end_position = gene_coordinates[2]

print(chromosome, start_position, end_position)

  • This tuple represents a chromosome identifier and two coordinate values. Tuples can be useful for representing fixed records, coordinate pairs, parameter combinations, or multiple values returned by a function. Python also supports tuple unpacking, which allows the elements to be assigned to separate variables in one statement.

chromosome, start, end = (“chr1”, 12500, 13800)

gene_length = end – start + 1

print(gene_length)

  • The calculation assumes that the coordinates are one-based and inclusive, as commonly used in formats such as GFF. Other biological formats, including BED, use zero-based, half-open coordinates. Coordinate conventions must therefore be checked before calculating genomic interval lengths or comparing positions across files. A tuple is a convenient container, but it does not itself validate the biological meaning of its values.
  • A set is an unordered collection of unique, hashable elements. Duplicate values are automatically removed, making sets particularly useful for identifying distinct genes, species, sequence identifiers, variants, or experimental conditions. Sets can be created with curly braces or the set() function. An empty set must be created using set() because {} creates an empty dictionary.

genes_sample_1 = {“BRCA1”, “TP53”, “EGFR”, “MYC”}

genes_sample_2 = {“TP53”, “MYC”, “KRAS”}

shared_genes = genes_sample_1 & genes_sample_2

all_genes = genes_sample_1 | genes_sample_2

unique_to_sample_1 = genes_sample_1 – genes_sample_2

print(“Shared:”, shared_genes)

print(“All genes:”, all_genes)

print(“Unique to sample 1:”, unique_to_sample_1)

  • Set operations are especially useful in comparative genomics and transcriptomics. Intersection identifies elements shared between datasets, union combines distinct elements, and difference identifies elements present in one set but absent from another. These operations can help compare gene lists from experiments, identify shared protein families, or examine overlap between variant sets. Because sets do not preserve a meaningful positional order, they should not be used when the original sequence of elements must be retained.
  • Set elements must be hashable, which generally means that their hash values remain stable while they are members of the set. Strings, integers, and many tuples containing only hashable elements can be used as set members, whereas lists and dictionaries cannot. Sets are often efficient for membership tests, such as determining whether a gene identifier belongs to a known list of genes.
  • A dictionary is a mutable collection of key-value pairs. Each key identifies an associated value, allowing data to be retrieved by a meaningful identifier rather than a numerical position. Dictionaries are created using curly braces with key-value pairs separated by colons. Keys must be hashable and unique within a dictionary, while values may be objects of different types.

gene_expression = {

    “BRCA1”: 12.5,

    “TP53”: 8.7,

    “EGFR”: 15.2,

    “MYC”: 20.1

}

print(gene_expression[“TP53”])

  • In this example, gene names serve as keys and expression measurements serve as values. Dictionaries are useful for associating genes with expression levels, proteins with functional annotations, organisms with taxonomic classifications, and variants with their predicted consequences. They also support efficient retrieval by key in typical use cases, making them well suited to many lookup tasks.
  • Dictionary values can be updated, new key-value pairs can be added, and existing entries can be removed. The get() method provides a convenient way to retrieve a value without raising a KeyError when a key is absent. Dictionary comprehensions allow dictionaries to be constructed from existing data.

gene_expression = {

    “BRCA1”: 12.5,

    “TP53”: 8.7,

    “EGFR”: 15.2

}

gene_expression[“TP53”] = 9.1

gene_expression[“MYC”] = 20.1

value = gene_expression.get(“KRAS”, 0)

print(gene_expression)

print(“KRAS value:”, value)

  • The default value of zero in this example is a programming choice, not a universal biological interpretation. In scientific data, a missing gene measurement may mean that the gene was not detected, was not measured, or was excluded during preprocessing. Missingness should not automatically be interpreted as zero expression.
  • Dictionaries can contain nested dictionaries, lists, tuples, or other structures. A gene annotation record, for example, might contain its chromosome, coordinates, strand, gene symbol, and associated transcripts. A dictionary can represent each gene as a key whose value is another dictionary containing these fields. This approach is flexible, although formal schemas, dataclasses, or tabular data structures may be preferable for large, standardized datasets.

gene_annotation = {

    “BRCA1”: {

        “chromosome”: “chr17”,

        “start”: 43044295,

        “end”: 43125483,

        “strand”: “-“

    },

    “TP53”: {

        “chromosome”: “chr17”,

        “start”: 7661779,

        “end”: 7687550,

        “strand”: “-“

    }

}

print(gene_annotation[“BRCA1”][“chromosome”])

print(gene_annotation[“BRCA1”][“start”])

  • Strings are another essential Python data structure, particularly in sequence analysis. A string is an immutable sequence of characters and is commonly used to represent DNA, RNA, and protein sequences. Strings support indexing, slicing, searching, counting, and transformations such as converting letters to uppercase. Because strings are immutable, operations that appear to modify a string actually create a new string.

dna = “atgcgcttaa”

dna = dna.upper()

print(“DNA:”, dna)

print(“Length:”, len(dna))

print(“G count:”, dna.count(“G”))

print(“C count:”, dna.count(“C”))

  • Strings are convenient for small and moderate sequences, but repeatedly creating new strings during processing of extremely large datasets can increase memory and computational costs. Sequence-analysis libraries, generators, and streaming approaches may be more appropriate when processing large numbers of records. For reliable biological analysis, strings should also be validated against the permitted alphabet and the rules of the relevant sequence format.
  • Arrays are collections designed for efficient storage and manipulation of data, particularly numerical values. Python lists can contain objects of different types, but NumPy arrays typically store elements using a consistent data type and support vectorized mathematical operations. This makes arrays useful for large numerical datasets such as gene-expression matrices, variant measurements, genomic signals, and model inputs.

import numpy as np

expression = np.array([12.5, 8.7, 15.2, 20.1])

print(“Mean expression:”, expression.mean())

print(“Maximum expression:”, expression.max())

print(“Values above 10:”, expression[expression > 10])

  • NumPy supports multidimensional arrays, mathematical transformations, broadcasting, and linear algebra. A two-dimensional array can represent a matrix in which rows correspond to genes and columns correspond to samples, or vice versa. The orientation must be documented because it affects the interpretation of calculations. NumPy is especially useful for numerical computation, while pandas provides additional functionality for labeled, tabular data.
  • A pandas DataFrame is a two-dimensional data structure organized into rows and columns, with labels for both dimensions. DataFrames are widely used in bioinformatics for gene-expression tables, clinical or experimental metadata, variant annotations, and statistical results. A Series represents a one-dimensional labeled collection. These structures provide methods for filtering, joining, grouping, handling missing values, and reading or writing common data formats.

import pandas as pd

data = {

    “Gene”: [“BRCA1”, “TP53”, “EGFR”],

    “Expression”: [12.5, 8.7, 15.2]

}

df = pd.DataFrame(data)

high_expression = df[df[“Expression”] > 10]

print(high_expression)

  • DataFrames are particularly useful when biological observations have multiple attributes that must remain associated. For example, a variant table may contain chromosome, position, reference allele, alternate allele, quality score, and predicted effect. Keeping these fields in labeled columns reduces the risk of losing the relationship between an observation and its annotations. For very large genomic datasets, specialized formats and tools may be needed because loading an entire table into memory can be impractical.
  • Other data structures are important for representing relationships and processing workflows. A stack follows the last-in, first-out principle, meaning the most recently added item is removed first. A queue follows the first-in, first-out principle, meaning the earliest added item is processed first. Stacks can support parsing, backtracking, and certain recursive algorithms, while queues are useful for scheduling computational tasks and managing work in a processing pipeline.
  • A linked list consists of nodes that contain values and references to other nodes. Although linked lists are important in computer science, Python lists and other built-in structures are usually more convenient for ordinary bioinformatics applications. Linked lists may be useful when studying particular algorithms or implementing specialized operations, but they are not automatically more efficient than Python lists for typical workloads.
  • Trees are hierarchical data structures in which nodes are connected through parent-child relationships. They are important in phylogenetics, where evolutionary trees represent relationships among organisms, genes, or sequences. Trees are also used in parsing structured data, searching, indexing, and representing hierarchical classifications. A phylogenetic tree may contain internal nodes representing inferred common ancestors and terminal nodes representing sampled taxa or sequences.
  • Graphs represent objects as vertices or nodes connected by edges. Graphs may be directed or undirected, weighted or unweighted, and can represent complex relationships that are not naturally hierarchical. In bioinformatics, graphs are used to model protein-protein interaction networks, metabolic pathways, gene-regulatory networks, molecular interaction systems, and sequence relationships. Genome assembly graphs and pangenome graphs represent alternative paths through genomic sequence information, helping researchers analyze repeated regions, structural variation, and diversity across individuals.
  • A hash table is a data structure that stores key-value associations using a hash function to determine where entries are stored. Python dictionaries and sets are implemented using hash-based techniques. These structures generally provide efficient average-case insertion, lookup, and deletion, although performance depends on the data and implementation. In bioinformatics, hash-based lookups are useful for matching sequence identifiers, checking whether a gene has already been processed, mapping variants to annotations, and detecting duplicate records.
  • Choosing the appropriate data structure depends on the task, the volume of data, the operations required, and the need to preserve order or uniqueness. A list is appropriate when order matters and elements may change. A tuple is suitable for a fixed group of related values. A set is useful when uniqueness and membership testing are important. A dictionary is appropriate when values must be retrieved through identifiers. NumPy arrays are often best for large numerical calculations, while pandas DataFrames are suitable for labeled tables. Trees and graphs are useful when the underlying data contains hierarchical or network relationships.
Data structureMain characteristicsExample bioinformatics use
ListOrdered, mutable, allows duplicatesStoring sequences or gene identifiers
TupleOrdered, generally immutableRepresenting coordinates or fixed records
SetUnique elements, efficient membership testingComparing gene lists or identifying unique variants
DictionaryKey-value mappingMapping gene identifiers to annotations
StringImmutable sequence of charactersDNA, RNA, and protein sequences
NumPy arrayEfficient numerical and multidimensional operationsExpression matrices and numerical analysis
pandas DataFrameLabeled rows and columnsGene-expression tables and variant annotations
StackLast-in, first-outParsing and backtracking algorithms
QueueFirst-in, first-outTask scheduling and pipeline processing
TreeHierarchical relationshipsPhylogenetic trees and taxonomies
GraphGeneral network relationshipsProtein interaction and metabolic networks
  • Data structure selection also affects algorithmic complexity. Accessing a list element by index is typically an O(1) operation, whereas searching an unsorted list for a particular value is generally O(n), where n is the number of elements. Set membership and dictionary key lookup are typically O(1) on average, although worst-case behavior can differ. Sorting a list generally requires O(n log n) time using Python’s built-in sorting algorithm. These complexity estimates help researchers anticipate how a program will behave as the number of sequences, genes, variants, or samples increases.
  • Memory efficiency is particularly important in genomics, where a dataset may contain millions of variants or a matrix may contain measurements for tens of thousands of genes across thousands of samples. Storing the same information repeatedly can waste memory, while an unsuitable representation may slow processing considerably. Dictionaries provide convenient lookups but may use more memory than compact numerical arrays. DataFrames offer useful labels and data-management operations but may be more expensive than specialized binary formats for certain large-scale tasks. Data should be represented according to its scientific meaning as well as its computational requirements.
  • Data structures also help preserve data quality and reproducibility. Gene identifiers should be consistent, genomic coordinates should use clearly specified conventions, and missing values should be distinguished from true zeros. Sets can remove duplicates, but removing duplicates indiscriminately may discard biologically meaningful observations. Dictionaries require unique keys, so using a gene identifier as a key may overwrite earlier records if the same identifier appears multiple times. When duplicate records are meaningful, a list of records or a DataFrame with multiple rows may be more appropriate.
  • In practical bioinformatics workflows, multiple data structures are often combined. A list may store sequence records, each represented by a dictionary containing its identifier and annotation. A dictionary may map each gene to a list of transcripts, while a set tracks the genes already encountered. A DataFrame may store the final measurements, and a graph may represent relationships among the resulting biological entities. Selecting and combining these structures thoughtfully makes it easier to build modular, efficient, and scientifically reliable analysis pipelines.
  • Understanding lists, tuples, sets, dictionaries, and other data structures is essential for developing Python skills in bioinformatics. These structures provide the foundation for handling biological sequences, organizing genomic annotations, processing numerical measurements, comparing datasets, and modeling complex biological relationships. Mastery of their properties, operations, limitations, and computational costs enables researchers to write clearer code and prepares them for advanced topics such as algorithms, database integration, sequence analysis, graph algorithms, and large-scale computational biology.
Author:

Leave a Reply

Your email address will not be published. Required fields are marked *