list previous or following list elements

antar2 desothier at yahoo.com
Thu Jun 26 23:52:50 CEST 2008


Hello


Suppose I have a textfile (text1.txt) with following four words:

Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:

I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b

import re
f = open('text1.txt', 'r')
list1 = []
list2 = []
for line in f:
	list1.append(line)
a = re.compile("^b")
int = 0
while(int <= list1[-1]):
	int = int + 1
	a_match = a.search(list1[int])
	if(a_match):
		list2.append(list1[int + 1])
print list2

I did not find information about addressing previous or following list
elements. So some help would be magnificent

Thanks a lot



More information about the Python-list mailing list