R337
R337

Reputation: 79

How do I loop through a list?

I'm trying to loop over a list, but unless I specify what section of the list to loop through, it doesn't work (I want it to loop over the WHOLE list not just one part e.g list1[1] etc.

input1 = input("Corrupted: ")
words = input1.split()
a = 0
final1 = ""
for i in words[a]:
  a = a + 1
  if i in "ATGC":
    final1 = final1 + i
print(final1)

When I run that, it prints out nothing. However, if I change the 'a' to a hard coded 0 it prints out the correct input for words[0] only. I don't understand since I assigned a to 0, and incremented it by 1 each time. It still didn't print anything!

Upvotes: 0

Views: 95

Answers (2)

Makoto
Makoto

Reputation: 106508

for i in words[a] does not do what you think it does. With a = 0, words[a] will always be length 1, with the zeroth element. So, your loop will only ever run once.

Iterate over the list directly instead:

for i in words:
    if i in "ATGC":
        final1 = final1 + i

Upvotes: 0

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

You can iterate directly over a list:

for i in words:
    if i in "ATGC":
        final1 = final1 + i
print(final1)

There are simpler ways to write this, like a list comprehension:

final1 = [i for i in words if i in "ATGC"]

Or for better performance using a frozen set, if you're dealing with single letters at a time in your input:

acids = frozenset(('A', 'T', 'G', 'C'))
final1 = [i for i in words if i in acids]

Either of those will return a list of strings - to get a single string back, use join:

print (''.join(final1))

Upvotes: 2

Related Questions