Skip to content

Instantly share code, notes, and snippets.

Embed
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()
@travis-cramer
Copy link

travis-cramer commented Oct 5, 2018

Hi Ratul, thanks for these useful Python tips. I'm really enjoying your medium article as well (https://medium.com/@ratulsaha/preparing-for-programming-interview-as-a-phd-student-with-python-5f8af8b40d5f) 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?
EDIT:
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?
Thanks!

@kennychenfs
Copy link

kennychenfs commented Aug 9, 2019

You should add:
arr[:-1]=[1,2,3]
or
arr[1:-1]=[2,3]
Nice job!

@offthewallace
Copy link

offthewallace commented Jul 25, 2020

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

@harih1290
Copy link

harih1290 commented Oct 24, 2020

a[len(a)-1]
list last number

@andrewphamvk
Copy link

andrewphamvk commented Jan 10, 2021

@harih1290 a[-1:] does the trick as well.

@aleglez22
Copy link

aleglez22 commented May 17, 2021

@harih1290 a[-1:] does the trick as well.

the actual equivalent is a[-1]

@j0nimost
Copy link

j0nimost commented Sep 17, 2021

You can also do crazy things like:

[5,4<<1, 6^1, 7+4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment