Dave Dave Dave Dave - 5 months ago 7
Python Question

How can I read 1 value from a list in python?

I know how to use

(list).pop(i)


I want to know if there is a better command.

In more detail:

a = [1,2,3,4,5,6]
a.pop(0) #This should equal 1


Unfortunately, pop removes the number from the sequence, so I was wondering if there was a better way.

I am a beginner, so please give simple/detailed answers.

Answer

Read a specific item in index i:

item = L[index]

Read a sequence of items from index 'start' to index 'stop':

seq = L[start:stop]

Iterate over a list:

for item in L:
    print item

If you need both the index and the item, use the enumerate function:

for index, item in enumerate(L):
    print index, item

You can also get the reversed list:

L.reverse()

Get list length:

length = len(L)

And there are so much more operations you can perform on lists.

Comments