简体   繁体   中英

How can I print the second element in this list?

friends = ["John", "Mark", "James"]
for friend in friends:
    print(friend)

How can I print the second element in this list using the for loop? I know how to get the second element in a list but I don't know how to get it using a for loop.

You could just do:

print(friends[1])

That would give the second element, it will output:

Mark

If you want to use a loop, try:

for i, v in enumerate(friends):
    if i == 1:
        print(v)

Output:

Mark

Python indexing starts from 0, so the second element's index would be 1.

The for loop I did iterates through the list, but the iterator i is the index of every element, and v is the value, so it check if i (the index) is 1 , if so, it prints v .

You can also use a counter for such problems. I've set it to 0 and for every iteration, it gets incremented by 1 . So, to access the 2nd element cnt would be 2 . You can add an if statement and print only Mark

friends = ["John", "Mark", "James"]
cnt=0
for friend in friends:
    cnt+=1
    if cnt==2:
         print(friend)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM