[Tutor] list slice
Jerry Hill
malaclypse2 at gmail.com
Mon Sep 15 17:30:24 CEST 2008
On Mon, Sep 15, 2008 at 10:56 AM, Norman Khine <norman at khine.net> wrote:
> Hello,
> I have this code:
>
> topics = object.parent.get_topics()
> for i, topic in enumerate(topics):
> all_previous_topics = topics[:i]
> print all_previous_topics
>
> where topics returns a list.
>
> I am trying to get all the topics before current topic in the loop.
>
> Is there a way to do this?
Yes.
Is topics a list, or a function which returns a list? What you've
written above works for me when topics is a list. In what way doesn't
it work for you?
>>> topics = ['Reading', 'Writing', 'Arithmetic']
>>> for i, topic in enumerate(topics):
print "Current Topic: ", topic
print "Previous Topics: ", topics[:i]
Current Topic: Reading
Previous Topics: []
Current Topic: Writing
Previous Topics: ['Reading']
Current Topic: Arithmetic
Previous Topics: ['Reading', 'Writing']
>>>
--
Jerry
More information about the Tutor
mailing list