Python Basics
This article is designed for beginners, introducing the basic usage of Python, including standard output, control statements, and common data structures, to help you quickly get started with problem-solving.
Standard Output
In Python, standard output is done using the print
function to display content in the console. By default, print
adds a newline at the end. To avoid this, you can use the parameter end=""
.
a = 10
# Output: 10
print(a)
# Concatenated output (by string concatenation or comma separation)
# Output: Hello, World!
print("Hello" + ", " + "World!")
# Use sep to specify a separator
print("Hello", "World!", sep=", ")
s = "abc"
# Output: abc 10
print(s, a)
# Formatted output
# Output: abc 10
print(f"{s} {a}")
Control Statements
Control statements in Python include conditional statements and loops. Below is a brief introduction.
Conditional Statements: if
, elif
, else
a = 10
if a > 5:
print("a > 5")
elif a == 5:
print("a == 5")
else:
print("a < 5")
# output: a > 5
Loops: for
/ while
The for
loop is typically used to iterate over iterable objects or sequences with a known range. The while
loop is used to repeatedly execute a block of code as long as a specified condition is met.
# Output: 0 1 2 3 4
for i in range(5):
print(i, end=" ")
print()
num = 100
# Output: 100 50 25 12 6 3 1
while num > 0:
print(num, end=" ")
num //= 2
print()
Basic Data Structures
Python offers a variety of built-in data structures, such as list
, deque
, dict
, and set
. Below is an introduction to some commonly used data structures and their usage.
List list
(Dynamic Array)
A list
in Python is a mutable sequence type, which can be used as a dynamic array.
Initialization method:
# initialize an empty list
nums = []
# initialize a list containing elements 1, 3, 5
nums = [1, 3, 5]
# initialize a list of size n with all elements as 0
n = 10
nums = [0] * n
# two-dimensional list with m rows and n columns, all elements are 1
m, n = 3, 4
matrix = [[1] * n for _ in range(m)]
Common Methods for Python Lists:
nums = [0] * 10
# Output: False
print(len(nums) == 0)
# Output: 10
print(len(nums))
# Insert an element 20 at the end of the list
nums.append(20)
# Output: 11
print(len(nums))
# Get the last element of the list, Output: 20
print(nums[-1])
# Remove the last element of the list
nums.pop()
# Output: 10
print(len(nums))
# Index access and modification
nums[0] = 11
# Output: 11
print(nums[0])
# Insert an element 99 at index 3
nums.insert(3, 99)
# Remove the element at index 2
nums.pop(2)
# Swap nums[0] and nums[1]
nums[0], nums[1] = nums[1], nums[0]
# Traverse the list
# Output example:
# 0 11 99 0 0 0 0 0 0 0
for num in nums:
print(num, end=" ")
print()
Double-ended Queue deque
deque
is a double-ended queue provided by the collections
module, allowing efficient insertion and deletion of elements at both ends.
from collections import deque
# initialize the deque
lst = deque([1, 2, 3, 4, 5])
# check if it's empty, output: False
print(len(lst) == 0)
# get the size, output: 5
print(len(lst))
# insert 0 at the head, 6 at the tail
lst.appendleft(0)
lst.append(6)
# get the head and tail elements, output: 0 6
print(lst[0], lst[-1])
# remove head and tail elements
lst.popleft()
lst.pop()
# insert 99 at index 2
lst.insert(2, 99)
# delete the element at index 1
del lst[1]
# traverse the deque
# output: 1 99 3 4 5
for val in lst:
print(val, end=" ")
print()
Queue
A queue is a data structure with restricted operations: elements can only be inserted at the back and removed from the front.
Python does not have a dedicated queue type, but you can use deque
to simulate a queue, where append
is equivalent to enqueue, and popleft
is equivalent to dequeue.
from collections import deque
# initialize the queue
q = deque()
# insert elements at the end of the queue
q.append(10)
q.append(20)
q.append(30)
# check if the queue is empty, output: False
print(len(q) == 0)
# size, output: 3
print(len(q))
# get the front element without dequeuing, output: 10
print(q[0])
# dequeue the front element
q.popleft()
# new front element, output: 20
print(q[0])
Stack
Although Python does not have a dedicated stack type, you can simulate a stack using list
or deque
. The append
method is equivalent to pushing onto the stack, and pop
is equivalent to popping from the stack.
# use list as stack
s = []
# push onto stack
s.append(10)
s.append(20)
s.append(30)
# check if empty, output: False
print(len(s) == 0)
# size, output: 3
print(len(s))
# top element of stack, output: 30
print(s[-1])
# pop from stack
s.pop()
# new top element of stack, output: 20
print(s[-1])
Dictionary dict
(Hash Table)
dict
is Python's implementation of a hash table, storing data in key-value pairs. The average time complexity for search, insertion, and deletion operations is O(1).
# initialize dictionary
hashmap = {1: "one", 2: "two", 3: "three"}
# check if it is empty, output: False
print(len(hashmap) == 0)
# size, output: 3
print(len(hashmap))
# lookup key
# output: Key 2 -> two
if 2 in hashmap:
print(f"Key 2 -> {hashmap[2]}")
else:
print("Key 2 not found.")
# get the value for a key, return None if not present
# output: None
print(hashmap.get(4))
# insert new key-value pair
hashmap[4] = "four"
# get the newly inserted value, output: four
print(hashmap[4])
# delete key 3
del hashmap[3]
# check after deletion
if 3 in hashmap:
print(f"Key 3 -> {hashmap[3]}")
else:
print("Key 3 not found.")
# output: Key 3 not found.
# iterate through dictionary
# output:
# 1 -> one
# 2 -> two
# 4 -> four
for k, v in hashmap.items():
print(f"{k} -> {v}")
Set
A set
in Python is a hash-based collection used to store unique elements. It is commonly used for removing duplicates and quickly checking the existence of elements.
# initialize the set
hashset = {1, 2, 3, 4}
# check if empty, output: False
print(len(hashset) == 0)
# size, output: 4
print(len(hashset))
# find element
if 3 in hashset:
print("Element 3 found.")
else:
print("Element 3 not found.")
# output: Element 3 found.
# insert new element
hashset.add(5)
# remove element 2
# discard won't raise an error if element doesn't exist
# check after removal
if 2 in hashset:
print("Element 2 found.")
else:
print("Element 2 not found.")
# output: Element 2 not found.
# iterate over the set, output:
# 1
# 3
# 4
# 5
for element in hashset:
print(element)
Summary
The foundational knowledge provided above is sufficient for you to start practicing algorithm problems.
Of course, Python offers many other data structures and useful APIs that are not covered in this article. Some advanced data structures will be introduced in later chapters, and the APIs for each structure can be looked up in documentation as needed, so there's no need to memorize them all at once.
Next, I will guide you through some algorithm problems on LeetCode to help you quickly apply these data structures and get familiar with the problem-solving system.