Python range() Function in Bioinformatics

  • The range() function is one of the most commonly used built-in functions in Python. It is particularly useful when working with loops, numerical sequences, arrays, biological datasets, and computational analyses. In bioinformatics, researchers frequently need to process large collections of biological data, such as DNA sequences, RNA sequences, protein sequences, gene expression measurements, and genomic coordinates. The range() function provides a convenient way to repeat operations a specified number of times or access elements using numerical indexes.
  • For example, when analysing a DNA sequence, a researcher may need to examine each nucleotide, identify particular bases, count occurrences of specific nucleotides, or extract subsequences. Similarly, when processing genomic data, it may be necessary to examine individual positions within a chromosome or compare neighbouring nucleotides. The range() function can support these operations by generating sequences of integer values that control how loops are executed. 
  • Understanding range() is therefore an important foundation for learning Python programming and applying it to biological data analysis.

What is the range() Function?

  • The range() function is a built-in Python function that generates an immutable sequence of integers. It is commonly used with for loops to execute a block of code repeatedly.
  • Unlike a list, range() does not immediately create and store all the numbers in memory. Instead, it represents a sequence of numbers that can be accessed when needed. This makes it memory-efficient, particularly when working with large numerical ranges.

dna = “ATATATATATATACCCGG”

print(dna)

print(len(dna))

print(range(len(dna)))

Output: 

ATATATATATATACCCGG

18

range(0, 18)

for i in range(5):

    print(i)

x = 5

for i in range(x):

    print(i)

Output: 

0

1

2

3

4

Explanation:

In this example, range(5) generates five integer values, beginning with 0 and ending with 4. The variable i takes each value sequentially, and the print() statement displays it. An important characteristic of range() is that the stopping value is excluded. Therefore, range(5) generates five numbers, not six.

Syntax of the range() Function

Python supports three common forms of the range() function:

range(stop)

range(start, stop)

range(start, stop, step)

Each form provides a different level of control over the generated sequence. 

  1. range(stop)

This form accepts one argument, which specifies where the sequence stops.

for i in range(5):

    print(i)

Output:

0

1

2

3

4

The sequence starts automatically at 0 and continues up to, but does not include, 5.

  1. range(start, stop)

This form accepts two arguments: a starting value and a stopping value.

for i in range(2, 7):

    print(i)

Output:

2

3

4

5

6

Here, the sequence begins at 2 and ends at 6. The stopping value, 7, is excluded.

  1. range(start, stop, step)

This form accepts three arguments: a starting value, a stopping value, and a step size. The step determines how much the value increases or decreases during each iteration.

for i in range(0, 10, 2):

    print(i)

Output:

0

2

4

6

8

In this example, the sequence begins at 0 and increases by 2 during each iteration.

The step can also be negative, allowing the sequence to move backwards.

for i in range(5, 0, -1):

    print(i)

Output:

5

4

3

2

1

Explanation: Here, the sequence begins at 5 and decreases by 1 until it reaches the stopping boundary of 0, which is excluded.

Understanding range() with Indexing

One of the most important applications of range() is accessing individual elements in a list, string, or array using their indexes. Python uses zero-based indexing, meaning that the first element has index 0, the second has index 1, and so on.

Consider the following DNA sequence:

dna = “ATGCGTAC”

for i in range(len(dna)):

    print(i, dna[i])

Output:

0 A

1 T

2 G

3 C

4 G

5 T

6 A

7 C

In this example, len(dna) calculates the length of the DNA sequence, which is 8. The expression range(len(dna)) generates the indexes from 0 to 7. The expression dna[i] accesses the nucleotide at the current index. 

This approach is particularly useful when the analysis requires both the position and the nucleotide at that position.

The Difference Between range(), len(), and for

  • These three Python elements are frequently used together, but they perform different tasks.
    • range() generates a sequence of integers.
    • len() returns the number of elements in an object.
    • for is a loop statement that iterates over the elements of an iterable.

dna = “ATGC”

for i in range(len(dna)):

    print(dna[i])

Output:

A

T

G

C

Here, len(dna) returns 4, range(4) generates the indexes 0, 1, 2, and 3, and the for loop processes each index.

Understanding the relationship between these elements is essential when writing Python programs for biological sequence analysis.

Applications of the range() Function in Bioinformatics

The range() function is useful in several bioinformatics applications because biological data frequently consists of ordered sequences, numerical positions, and collections of measurements. The following examples demonstrate how it can be used in practical biological data analysis.

  1. Counting Nucleotides in a DNA Sequence

One common bioinformatics task is determining the number of occurrences of each nucleotide (adenine, thymine, guanine, and cytosine) in a DNA sequence.

dna = “ATGCGATACGTA”

A = 0

T = 0

G = 0

C = 0

for i in range(len(dna)):

    if dna[i] == “A”:

        A += 1

    elif dna[i] == “T”:

        T += 1

    elif dna[i] == “G”:

        G += 1

    elif dna[i] == “C”:

        C += 1

print(“A:”, A)

print(“T:”, T)

print(“G:”, G)

print(“C:”, C)

Output: 

A: 4

T: 3

G: 3

C: 2

In this example, range(len(dna)) generates the indexes corresponding to all nucleotide positions in the DNA sequence. The loop examines each position using dna[i] and increases the appropriate nucleotide counter.

This approach is useful for basic sequence composition analysis, which can be extended to calculate nucleotide frequencies and GC content.

  1. Calculating GC Content

GC content represents the percentage of guanine (G) and cytosine (C) nucleotides in a DNA sequence. It is an important characteristic in genomic analysis, microbial classification, comparative genomics, and sequence quality assessment.

The following example uses range() to count the G and C nucleotides.

dna = “ATGCGATACGTA”

gc_count = 0

for i in range(len(dna)):

    if dna[i] == “G” or dna[i] == “C”:

        gc_count += 1

gc_content = (gc_count / len(dna)) * 100

print(“GC content:”, gc_content, “%”)

Output:

GC content: 41.66666666666667 %

Here, the loop examines each nucleotide and increases gc_count whenever it encounters G or C. The total number of G and C nucleotides is then divided by the sequence length and multiplied by 100.

  1. Extracting Codons from a DNA Sequence

Codons are groups of three consecutive nucleotides that encode amino acids or termination signals during protein synthesis.

A DNA sequence can be examined in groups of three using the step argument of range().

dna = “ATGGCTTTACGA”

for i in range(0, len(dna), 3):

    codon = dna[i:i+3]

    print(codon)

Output:

ATG

GCT

TTA

CGA

In this example:

– 0 specifies the starting position.

– len(dna) determines the stopping boundary.

– 3 specifies the step size. 

The loop advances three positions at a time. The expression dna[i:i+3] extracts three consecutive nucleotides to form a codon.

This approach is useful when examining coding DNA sequences and identifying codons. In real sequence analysis, the correct reading frame and sequence orientation must also be considered.

  1. Examining Consecutive Nucleotide Positions

Sometimes researchers need to examine neighbouring nucleotides in a DNA sequence. This can be useful when investigating sequence patterns, identifying specific nucleotide arrangements, or analysing short sequence motifs.

For example, the following program examines pairs of neighbouring nucleotides:

dna = “ATGCGTAC”

for i in range(len(dna) – 1):

    pair = dna[i:i+2]

    print(pair)

Output:

AT

TG

GC

CG

GT

TA

AC

Here, range(len(dna) – 1) is used because each pair requires two consecutive nucleotides. The loop stops before the final position to ensure that every extracted pair contains two nucleotides.

This technique can be extended to examine dinucleotide frequencies, short sequence motifs, and local sequence patterns.

  1. Processing Gene Expression Data

Bioinformatics researchers frequently analyse gene expression datasets containing measurements for hundreds or thousands of genes across multiple biological samples.

Consider a simplified dataset containing expression measurements for four genes:

expression = [12.5, 18.3, 9.7, 25.4]

for i in range(len(expression)):

    print(“Gene”, i + 1, “:”, expression[i])

Output:

Gene 1 : 12.5

Gene 2 : 18.3

Gene 3 : 9.7

Gene 4 : 25.4

In this example, range(len(expression)) generates the indexes of the expression measurements. The loop accesses each measurement using expression[i].

This approach can be extended to calculate statistics, identify genes with high expression levels, and examine gene expression profiles.

  1. Processing Multiple Biological Samples

A gene expression dataset can also be represented as a two-dimensional list, where rows represent genes and columns represent samples.

Consider the following example:

expression = [

    [12, 15, 18],

    [20, 22, 19],

    [8,  10, 12],

    [30, 28, 35]

]

for i in range(len(expression)):

    for j in range(len(expression[i])):

        print(expression[i][j], end=” “)

    print()

Output: 

12 15 18

20 22 19

8 10 12

30 28 35

This example uses nested loops. The outer range() iterates through the genes, while the inner range() iterates through the samples associated with each gene.

Such nested loops are useful when processing multidimensional biological datasets, including gene expression matrices, genotype data, and other numerical measurements.

Using range() with NumPy Arrays

In bioinformatics, Python libraries such as NumPy are widely used for numerical computation and biological data analysis. NumPy arrays can represent large collections of numerical measurements, including gene expression values, nucleotide counts, and other quantitative biological information.

The range() function can be used to access NumPy array elements through their indexes.

For example:

import numpy as np

counts = np.array([12, 25, 18, 30, 15])

for i in range(len(counts)):

    print(“Sample”, i + 1, “:”, counts[i])

Output:

Sample 1 : 12

Sample 2 : 25

Sample 3 : 18

Sample 4 : 30

Sample 5 : 15

Here, range(len(counts)) generates the indexes of the NumPy array, and counts[i] retrieves the value at each position.

Although this approach works, NumPy also provides vectorized operations that can process entire arrays without explicitly writing loops. These operations are often more efficient for large datasets.

Important Considerations When Using range()

Although range() is straightforward, several characteristics should be understood to avoid common programming errors.

  • The stopping value is excluded. For example, range(1, 5) generates 1, 2, 3, and 4, but not 5. This is particularly important when working with biological sequence positions and extracting subsequences.
  • Python indexing starts at zero. The first nucleotide in a DNA string has index 0, not index 1. Therefore, a DNA sequence containing 100 nucleotides has indexes from 0 to 99.
  • The step cannot be zero. A statement such as range(0, 10, 0) produces a ValueError. The step must be a non-zero integer.
  • The range() function requires integer arguments. It cannot directly generate a sequence of floating-point numbers. For numerical sequences involving decimal values, NumPy provides alternatives such as numpy.arange() and numpy.linspace().
  • A range object is not a list. Although it behaves like a sequence of integers, it does not store every generated number separately. It stores the starting value, stopping value, and step size, calculating individual values when needed. This makes it memory-efficient when working with large ranges. 

range() and enumerate(): Understanding the Difference

Python provides another built-in function called enumerate(), which is often useful when processing biological sequences.

Consider the following DNA sequence:

dna = “ATGC”

for i in range(len(dna)):

    print(i, dna[i])

Output:

0 A

1 T

2 G

3 C

The same operation can be performed using enumerate():

dna = “ATGC”

for i, nucleotide in enumerate(dna):

    print(i, nucleotide)

Output:

0 A

1 T

2 G

3 C

Note:

  • Both approaches produce the same output.
  • The difference is that range(len(dna)) generates numerical indexes, whereas enumerate() provides both the index and the corresponding element directly.
  • For simple sequence iteration, enumerate() is often more readable. However, range() remains particularly useful when you need to control the starting position, stopping position, or step size explicitly.

Conclusion

  • The range() function is an important Python built-in function for generating sequences of integers and controlling repetitive operations. Its three forms allow programmers to specify starting values, stopping boundaries, and step sizes. When combined with for loops, indexing, and sequence operations, it provides a practical approach to processing biological data.
  • In bioinformatics, range() can be applied to DNA and RNA sequence analysis, nucleotide counting, GC content calculation, codon extraction, motif examination, gene expression processing, and multidimensional biological datasets. It also provides a foundation for understanding loops and indexing, which are essential concepts when working with Python libraries such as NumPy, pandas, and Biopython.
  • Although more advanced libraries offer efficient alternatives for processing large biological datasets, understanding range() helps researchers develop the programming skills needed to perform biological data analysis systematically and accurately.
Author:

Leave a Reply

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