Python Forum
making a list be in reverse
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
making a list be in reverse
#1
in a loop that builds a list i have this line of code:
        filelist[:0] = [openthis] # build this list in reverse
to build this list in reverse. my other option is to build it using list.append() and reversing the whole list after the loop. what i am wondering is which way would be more appropriate and which way would be faster in CPython.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Maybe a deque from the collections module would be useful.
https://docs.python.org/3/library/collec...ue-objects Wrote:class collections.deque([iterable[, maxlen]])
Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.
...
...
(see link for more info)
Reply
#3
the current project only needs a stack. you know, a one sided end where the logic pushes and pops. actually, it just iterates the list after using the last pushed item one or two times. files get opened when creating the stack and must be closed in reverse order so that anything buffered in one is written to the next file which will be closed next. these are compress files, that would be stacked if the file has an extension stack like "foo.gz.bz2.xz". or the file is read in which case the close order is unimportant.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020