akkapolk
akkapolk

Reputation: 594

How to print index: value when loop a list in Python

In C#:

List<string> stringList = new List<string>() { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE" };
for (int i = 0; i < stringList.Count; i++)
    Console.WriteLine(i + ": " + stringList[i]);

Output:

0: AAAA
1: BBBB
2: CCCC
3: DDDD
4: EEEE

In Python:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(i + ": " + string)

I want output same as the output above, but there is error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Upvotes: 0

Views: 532

Answers (4)

akkapolk
akkapolk

Reputation: 594

I must use str() as per @RoadRunner comment, it will look like the C# which I want

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i in range(len(stringList)):
    print(str(i) + ": " + stringList[i])

or

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(str(i) + ": " + string)

Upvotes: 0

Emma
Emma

Reputation: 27723

I guess your code is just fine, maybe just a bit modify it:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(f'{i}:  {string}')

Output

0:  AAAA
1:  BBBB
2:  CCCC
3:  DDDD
4:  EEEE

You can also write with list comprehension, if you like:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
[print(f'{i}:  {string}') for i, string in enumerate(stringList)]

Or you can simply build your output first and then print only once:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
output = ''
for i, string in enumerate(stringList):
    output += f'{i}: {string}\n'

print(output)

Upvotes: 4

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521179

Just use a while loop:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
i = 0
while i < len(stringList):
    print(str(i) + ": " + stringList[i])
    i = i + 1

Upvotes: 0

Shishir Naresh
Shishir Naresh

Reputation: 763

Try the below code, Hope this helps:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(i ,": ", string)

Ouput will be :

0 :  AAAA
1 :  BBBB
2 :  CCCC
3 :  DDDD
4 :  EEEE

Upvotes: 4

Related Questions