Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using list comprehension to overwrite a variable based on condition

I have a list of DNA sequences (seqs), and I’m trying to use a list comprehension to find the length of the longest sequence. Essentially, I’m trying to turn this into a list comprehension:

longest_sequence = 0
for sequence in seqs:
    if len(sequence) > longest_sequence:
        longest_sequence = len(sequence)

This is what I thought the list comprehension would look like:

[(longest_sequence = len(sequence)) for sequence in seqs if len(sequence) > longest_sequence]

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks.

>Solution :

List comprehensions are used to obtain lists. With a list comprehension, each element in some input list/iterable goes through some filter/map/conditional logic to obtain an output list.

In your case, you need a scalar (just one number), not a list.

So you’re not helped that much by using list comprehension. But if you want to use it, you can use a list comprehension to obtain a list of the lengths, then just take the max of that list, as such:

lengths = [len(seq) for seq in seqs]
longest_length = max(lengths)

Keep in mind that both this code and your code will output the maximum length, not the sequence with the maximum length.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading