In this method, we count each nucleotide by creating a dictionary and updating it while looping through the DNA sequence. This approach does not require any extra modules and helps you understand how counting works step by step.
| Code |
| dna = “ATGCGCATG” counts = {} for base in dna: if base in counts: counts[base] += 1 else: counts[base] = 1 print(counts) |
| Code (shorter version) |
| dna = “ATGCGCATG” counts = {} for base in dna: counts[base] = counts[base] + 1 if base in counts else 1 print(counts) |
Step-by-Step Explanation
- Store the DNA Sequence
| dna = “ATGCGCATG” |
We first store the DNA sequence in a variable called dna.
- Create an Empty Dictionary
| counts = {} |
An empty dictionary is created to store the count of each nucleotide.
- Key → the nucleotide (A, T, G, or C)
- Value → how many times it appears
- Loop Through Each Nucleotide
| for base in dna: |
The for loop goes through every character in the DNA string one by one.
In each iteration, the current character is stored in the variable base.
- Check and Update the Count
| if base in counts: counts[base] += 1 else: counts[base] = 1 |
This is the core logic:
- If the nucleotide already exists in the dictionary → increase its count by 1.
- If the nucleotide does not exist yet → add it to the dictionary with a count of 1.
- Print the Final Result
| print(counts) |
| Output: |
| {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2} |
We have generated a dictionary named counts which has the value {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2}.
| counts: {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2} |
How the Dictionary Builds Up
| Step | Current Base | Action Taken | Dictionary State |
| 1 | A | Add A with count 1 | {‘A’: 1} |
| 2 | T | Add T with count 1 | {‘A’: 1, ‘T’: 1} |
| 3 | G | Add G with count 1 | {‘A’: 1, ‘T’: 1, ‘G’: 1} |
| 4 | C | Add C with count 1 | {‘A’: 1, ‘T’: 1, ‘G’: 1, ‘C’: 1} |
| 5 | G | Increase G to 2 | {‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 1} |
| 6 | C | Increase C to 2 | {‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 2} |
| 7 | A | Increase A to 2 | {‘A’: 2, ‘T’: 1, ‘G’: 2, ‘C’: 2} |
| 8 | T | Increase T to 2 | {‘A’: 2, ‘T’: 2, ‘G’: 2, ‘C’: 2} |
| 9 | G | Increase G to 3 | {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2} |
Summary
This method works by:
- Creating an empty dictionary.
- Checking each nucleotide one by one.
- Either adding a new nucleotide or increasing the count of an existing one.
It is a clear and fundamental way to count items in Python before using more advanced tools like collections.Counter.