Skip to main content

Python

Last updated: 5 Aug 2020 ·
Posted in wiki#notes

Common list operations

# Initialize an empty list
>>> s = [] # or
>>> s = list()

# Create a list
>>> s = ["Chess", "Go"]

# Get length of list
>>> len(s)
2

# Add an item to end of list
>>> s.append('Hex')
>>> s
["Chess", "Go", "Hex"]

# Remove an item from end of list
>>> s = ["Chess", "Go", "Monopoly", "Hex"]
>>> s.pop()
"Hex" # Returns the removed item
>>> s
["Chess", "Go", "Monopoly"]
>>> s.pop(1) # Remove item at index 1
"Go"
>>> s
["Chess", "Monopoly"]

# Add an item at an index
>>> s.insert(1, "KenKen")
>>> s
["Chess", "KenKen", "Go"]

# Remove the first item from the list whose value is equal to x
>>> s.remove("Chess")
["KenKen", "Go"]

# Get index of first occurence of item in list
>>> s = ["Monkey", "Carrot", "Red", "Carrot"]
>>> s.index("Carrot")
1

# Get total occurrences of item in list
>>> s = ["Monkey", "Carrot", "Red", "Carrot"]
>>> s.count("Carrot")
2

# Check if an element exists in list
>>> s = ["Chess", "KenKen", "Go"]
>>> "Go" in s
True
>>> "Monopoly" in s
False
>>> "Go" not in s
False

# Concatenate multiple lists
>>> s = ["Chess", "Go"]
>>> s + ["Hex"]
["Chess", "Go", "Hex"]

# Get the smallest/largest item of list
>>> s = [10, 6, 89, 37]
>>> min(s)
6
>>> max(s)
89

# Slicing a list with list[start:end] (end is exclusive)
>>> s = ["Monkey", "Carrot", "Red", "Carrot"]
>>> s[1:3]
['Carrot', 'Red']

# Slicing a list with step with list[start:end:step]
>>> s = [1, 3, 5, 6, 7, 8]
>>> s[1:5:2]
[3, 6]

# Create a shallow copy of list
>>> s_copy = s.copy() # or
>>> s_copy = s[:]

# Create a deep copy of list
>>> import copy
>>> s_deepcopy = copy.deepcopy(s)

# Remove all items from list
>>> s.clear() # or
>>> del s[:]

# Reverse a list
>>> s[::-1] # Returns a new list
>>> s.reverse() # Reverses list in place

# Extend a list by appending all items from another iterable
>>> s = ["Chess", "Go"]
>>> s.extend(["Hex", "Shogi"])
>>> s
["Chess", "Go", "Hex", "Shogi"]

# Sort a list
>>> s = ["Chess", "Go", "Hex", "Shogi"]
>>> s.sort() # Sort list in place
# sorted(s) returns a new sorted list
>>> s
['Chess', 'Go', 'Hex', 'Shogi']

Easter eggs

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> import antigravity
>>> import __hello__
Hello world!
>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

Snippets

# Multiple assignment
>>> x, y = 2, 3 # or
>>> x, y = (2, 3) # or
>>> x, y, z = 'abd'

# Get Python version
>>> import sys
>>> sys.version
'3.8.10 (default ...)'

# Get Unix timestamp
>>> import time
>>> time.time()
1636620498.0040886

# Check the type of object
>>> n = 34
>>> type(n)
<class 'int'>
>>> st = "Hello, world!"
>>> type(st)
<class 'str'>

# Count the number of unique characters in a string
len(set("stackoverflow"))

# Check if an element in one list exists in another
any(e in list2 for e in list1)