'How to print an index 0 of a list, with for loop?
Why does this code, does not return (or print) the 0 index of the list?
N = int(input())
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
for i in range(N):
print(letters[i]*i)
output: should be:
A
BB
CCC
DDDD
EEEEE
FFFFFF
GGGGGGG
But im getting this, without the "A":
B
CC
DDD
EEEE
FFFFF
GGGGGG
Solution 1:[1]
Because i starts counting at zero.
If you type:
for i in range(10):
print(i)
You'll see:
0
1
2
3
4
5
6
7
8
9
If you want to count from 1 to N instead of 0 to N-1, type:
print(letters[i]*(i+1))
Solution 2:[2]
Because 0 times a list wont print it. You need to add 1.
N = int(input())
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
for i in range(N):
print(letters[i]*(i+1))
Solution 3:[3]
the for i in range starts at 0. It then tries to execute
print(letters[i]*i)
At index 0, this translates to
print(letters[0]*0)
Since the resulting string is multiplied by zero, it outputs nothing. Changing i to i + 1 would solve this issue, as other commenters have pointed out.
Solution 4:[4]
the i starts from 0. So you need:
for i in range(N):
print(letters[i]*(i+1))
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 | esquisilo |
| Solution 2 | Niteya Shah |
| Solution 3 | shell_ |
| Solution 4 | SeanH |
