list previous or following list elements

Terry Reedy tjreedy at udel.edu
Fri Jun 27 00:24:15 CEST 2008



antar2 wrote:
> Hello
> 
> 
> Suppose I have a textfile (text1.txt) with following four words:

I see seven.  Just say 'list of 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

I believe
wordlist = open('words.txt','r').read().split('\n')
should give you the list in Python.  In any case,

wordlist = ['Apple','balcony', 'cartridge',
'damned', 'paper', 'bold', 'typewriter']
for i, word in enumerate(wordlist):
     if word[0] == 'b':
         print(wordlist[i+1]) # 3.0
         break

#prints cartridge (in 3.0)




More information about the Python-list mailing list