Reputation: 41
I want to print and save letters of this word "complexity"; I want to iterate through the word and get every letter that has an even number as its index, store or save it in a list, and also get every letter that has an odd number as its index and save it as a list in their respective variables. Below is the code.
word = "complexity"
even_letters = ""
odd_letters = ""
for index in range(0,len(word)):
if int(index) % 2 == 0:
even_letters = word[index]
else:
odd_letters = word[index]
print(list(even_letters))
print(list(odd_letters))
But my results shows only this:
['t']
['y']
What am I doing wrong?
Upvotes: 1
Views: 2677
Reputation: 1135
This can be done more easily with list comprehensions:
even_letters = [c for i, c in enumerate(word) if i % 2 == 0]
odd_letters = [c for i, c in enumerate(word) if i % 2 == 1]
Upvotes: 1
Reputation: 91
If, as you said, you want to save the different letters as a list then you even_letters and odd_letters must be initialized as lists and you must append the letters, not reseting their value. If I were you I would also use the enumerate option in python so you can get the index and the letter at the same time.
word = "complexity"
even_letters = []
odd_letters = []
for index, letter in enumerate(word):
if index % 2 == 0:
even_letters.append(letter)
else:
odd_letters.append(letter)
print(list(even_letters))
print(list(odd_letters))
If you want to obtain a string instead of a list, then you can change even_letters = letter and odd_letters = letter for even_letters += letter odd_letters += letter
Upvotes: 1
Reputation: 45806
You're overwriting the strings instead of adding to them.
Change
even_letters = word[index]
To
even_letters += word[index]
=
reassigns (overwrites). +=
appends (add to).
Upvotes: 2