Home > OS >  how can I show the order of list's elements in python?
how can I show the order of list's elements in python?

Time:12-13

In c, c when we say

For i=0 ;i<10 ;i  
Printf(i)

It prints the order used in the iretation 0,1,2... but in python I have this example :

friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends:
    print('Happy New Year:', friend)

I want to print the oder of the elements, Joseph is 0, Glenn is 1.. Etc, i know i can use a count=count 1 to print it, but I see print order knows already the order of elements, so is there a way similar to c to print the order of elements directly?

CodePudding user response:

You can use the enumerate function to get the index of items in a list:

for idx, friend in enumerate(friends):
    print('Happy New Year:', idx, friend)

CodePudding user response:

Try this:

for index, friend in enumerate(friends):
    print(friend, " is ", index)

To learn more read this

CodePudding user response:

You can use enumerate:

friends = ['Joseph', 'Glenn', 'Sally']
for i, friend in enumerate(friends):
    print(f"{friend} is {i}")

Output:

Joseph is 0
Glenn is 1
Sally is 2

CodePudding user response:

The closest analog to a C-style for loop is to use range to use an index for a sequence rather than element by element iteration:

friends = ['Joseph', 'Glenn', 'Sally']
for i in range(0,len(friends)):
    print(i, friends[i])

Prints:

0 Joseph
1 Glenn
2 Sally

As others have said, you can also use enumerate to create a tuple of index, element from a sequence:

for t in enumerate(friends):
    print(t)

(0, 'Joseph')
(1, 'Glenn')
(2, 'Sally')

Which can be unpacked into two variables:

for idx, name in enumerate(friends):
    print(idx, name)

Prints:

0 Joseph
1 Glenn
2 Sally
  • Related