Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous object without len(list)

Tags:

python

list

How to get previous or next object with this format of code?

alignment = [[a,b,c],[2,3,4],[q,w,e]]

for obj in alignment:
    some code here to get previous object

I know how to do that with:

for i in range(0,len(alignment)):
    alignment[i-1][objIndex]
like image 310
Rade Tomovic Avatar asked May 21 '15 10:05

Rade Tomovic


People also ask

How do I get past elements in a list?

To access the next element in list , use list[index+1] and to access the previous element use list[index-1] .

Can you use LEN () on a list?

The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.

How do you exclude items from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.


2 Answers

You can use enumerate :

alignment = [[a,b,c],[2,3,4],[q,w,e]]

for index,obj in enumerate(alignment):
    alignment[index-1] # pre
    alignment[index+1] # next

Note that as a more efficient way for accessing to next items and refuse of multiple indexing you can use iter() function to create an iterator object from your list (from second element to end) and access to next elements in each iteration with next :

>>> l=[1,2,3,4]
>>> it=iter(l[1:])
>>> for i in l :
...   print i,next(it,None)
... 
1 2
2 3
3 4
4 None

Note that if you don't pass the None as the second argument to next() function it will raise a StopIteration error.You can also handle it with a try-except statement.

Also for short lists you can use zip function and for long lists itertools.izip() function (zip in python 3):

>>> for i,j in zip(l,l[1:]):
...   print i,j
... 
1 2
2 3
3 4

zip(l,l[1:]) will give you the following pairs of items :

[(1, 2), (2, 3), (3, 4)]

and in the loop you can use i as the current item then j will be the next item or use j as the current then i will be the previous!:)

like image 73
Mazdak Avatar answered Oct 22 '22 10:10

Mazdak


There are many different options depending on what your use for the neighbour entry is. For instance, if you only want to process pairs, and not modify the list:

for left,right in zip(somelist[:-1], somelist[1:]):
  pass

Or if you need to keep the prior entry as a reference:

prev = None
for item in somelist:
  pass
  prev = item

None here is used in place of a prior item for the first, similar to how it's used for the next item after the last in Kasra's iter()-based example.

like image 1
Yann Vernier Avatar answered Oct 22 '22 12:10

Yann Vernier