Skip to content

Instantly share code, notes, and snippets.



Last active Oct 24, 2020
What would you like to do?
Useful List tricks in Python
#List traversal
range(start, stop, hop)
range(n) # [0,1,...,n-1]
range(1,n) # [1,...,n-1]
range(1,n,2) # [1,3,5,...,n-1] if n is even, or [1,3,5,...,n-2] if n is odd
range(n,-1,-1) # [n,n-1,n-2,...,0]
range(len(arr)) # Provides indices of an array arr
range(len(arr)-1,-1,-1) # Provides indices of arr backwards
# List slicing
arr[w:s] # Wait w elements, start copy (:), stop before reaching index s
arr = [1,2,3,4]
arr[1:] = [2,3,4]
arr[:2] = [1,2]
#List manipulation
arr = [1,2,3]
[str(x) for x in arr] # Output: ['1','2','3']
map(lambda x: str(x), arr) # Output: ['1','2','3']
[str(x) for x in arr if x%2] # Output: ['1','3']
# List as queue
arr = [1,2,3]
arr.append(x) # queue.push(x)
arr.pop(0) #queue.pop()
arr[0] #queue.peek()
# List as stack
arr = [1,2,3]
arr.append(x) #stack.push(x)
arr.pop() # stack.pop()
arr[-1] # stack.peek()

This comment has been minimized.

Copy link

@travis-cramer travis-cramer commented Oct 5, 2018

Hi Ratul, thanks for these useful Python tips. I'm really enjoying your medium article as well ( as I study for my upcoming interview.
Just a quick question:
About these "list as queue" and "list as stack" operations at the bottom of this file (they're really nice and pythonic--I love it, but), don't the push and pop methods occur in O(n) time whereas a properly implemented queue/stack would take O(1) time?
After reading into it a little more, it looks like the only method that gives us some time complexity "trouble" is:

  • arr.pop(0) would take O(n) whereas a properly implemented queue would take O(1)

The rest, arr.append(x), arr.pop(), and of course the "peeks" would be O(1) just like a properly implemented queue/stack.
What are your thoughts here?


This comment has been minimized.

Copy link

@kennychenfs kennychenfs commented Aug 9, 2019

You should add:
Nice job!


This comment has been minimized.

Copy link

@offthewallace offthewallace commented Jul 25, 2020

arr[::-1]=[4,3,2,1] I just find this reverse string pretty cool


This comment has been minimized.

Copy link

@harih1290 harih1290 commented Oct 24, 2020

list last number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.