svlk
svlk

Reputation: 531

How to create a list without using range in Python (For Loops)?

Let's say I have

myString = "ORANGE"

How can I write a for-each loop that lists each character so it looks like this

1O
2R
3A
4N
5G
6E

I am confused as I don't know how to do it without using range.

Upvotes: 3

Views: 2088

Answers (5)

imk
imk

Reputation: 384

try this

myString = "ORANGE"
for id, val in enumerate(myString, 1):
    print("".join(str(id) + val))

Upvotes: 0

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

Simple way to do this:

myString = "ORANGE"
for i in range(0,len(myString)):
    print (str(i+1)+""+myString[i])

Without using range:

myString = "ORANGE"
j=1
for i in myString:
    print (str(j)+""+i)
    j+=1

Upvotes: 1

Xantium
Xantium

Reputation: 11605

This is quite basic. 5 answers and none of them actually say this I am surprised. Never mind this should do what you asked for:

myString = "ORANGE"
a = 1

for i in myString:

    print(str(a) + i)
    a = a + 1

Upvotes: 2

blakev
blakev

Reputation: 4449

for index, character in enumerate('ORANGE'):
    print('{}{}'.format(index + 1, character))

Python docs on enumerate

Upvotes: 1

Transhuman
Transhuman

Reputation: 3547

myString = "ORANGE"
l = [str(i)+j for i,j in enumerate(myString,1)]
' '.join(l)

Output:

'1O 2R 3A 4N 5G 6E'

Upvotes: 1

Related Questions