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.
This comment has been minimized.
You should add: |
This comment has been minimized.
This comment has been minimized.
arr[::-1]=[4,3,2,1] I just find this reverse string pretty cool |
This comment has been minimized.
This comment has been minimized.
|
This comment has been minimized.
This comment has been minimized.
@harih1290 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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:
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!