简体   繁体   中英

How to print elements of particular index in list in python?

Suppose I have list as lists=[1,2,3,3,4,43] now i want to access 5 index element from the above list how can i do that? I Tried sorting the list

lists.sort()
z=len(lists)
lists.index(z-1)

on trying to get 5th item ie 4 it says value not in list. how can I do that?

lists.index(z-1)

index() is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears.

In your case z=6 and z-1=5, as 5 is not present in the list it returns

ValueError: 5 is not in list

To get value use following

lists[z-1]

it will return the value at the given index ie. value at z-1 index

To get the 5th index you should do: 'list[4]'

What you tried 'list.index(6-1)' will return the index of the first value that equals 5

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