Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a string in a list and its index on the same line?

This probably has a very simple solution, but I'm just a beginner.

What I have is:

def content(L):  
    for i in range(len(L)):  
        print (i), (L[i])

Right now it only prints the index and not the string. I'm not entirely sure what the issue is, but when I switch the ordering in the last line so that (L[i]) comes first then it prints the string but not the index. I want to print both on the same line.

like image 663
NavesinkBanks Avatar asked Dec 10 '25 14:12

NavesinkBanks


1 Answers

In Python 3.x, print is not a statement as in Python 2.x, but rather a function. You can use it like this:

print(i, L[i])

Additionally, enumerate is great for what you're trying to do:

for i, c in enumerate(L):
    print(i, c)

Note that you can use print as a Python 3.x-style function in Python 2 if you import it from the __future__ package (for Python 2.6 and up):

from __future__ import print_function
like image 50
George Bahij Avatar answered Dec 13 '25 04:12

George Bahij