'Why is my Python code printing only even indices? [duplicate]
You can clearly what I mean from the codes and console output.
file1 = open("texxt.txt", "r")
lines = file1.readlines()
all_names = []
for line in lines:
all_names.append(line.strip())
print(all_names)
for name in all_names:
print(all_names.index(name))
Console
> D:\Codes\Flutter\learningdart>python text.py
> ['19th Mile', '19th Mile', '1Password', '1Password', 'ActiveTrail', 'ActiveTrail','AdEspresso', 'AdEspresso']
>0
>0
>2
>2
>4
>4
>6
>6
In case you need the text file
19th Mile
19th Mile
1Password
1Password
ActiveTrail
ActiveTrail
AdEspresso
AdEspresso
Solution 1:[1]
If you want all indices using range() and len():
for index in range(len(all_names)):
print(index)
try this :
file1 = open("texxt.txt", "r")
lines = file1.readlines()
all_names = []
for line in lines:
all_names.append(line.strip())
print(all_names)
for index in range(len(all_names)):
print(index)
If you want name and indices both then:
for name in enumerate(all_names):
print(name)
Solution 2:[2]
You ask for index So the position of an element. You need to get the element using :
all_names[name]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | JoelCrypto |
