Numbers (int)
Overview
Python supports several numeric types including integers, long integers, and floating-point numbers.
- Integers: Basic whole numbers like 1, 11, 22, 36
- Long Integers: Extended integer values that maintain integer properties, such as 154864131, 548798466111131313
- Floating Point: Numbers with decimal points like 3.14, 0.78, 99.000000, 9999.8888888
1. Number Conversions
int(x, base=None) - Convert x to integer, base specifies conversion system
float(x) - Convert x to floating point number
complex(x) - Create complex number with real part x, imaginary part 0
complex(x, y) - Create complex number with real part x, imaginary part y
bit_length(x) - Minimum bits needed to represent number in binary
bin() - Convert decimal to binary
oct() - Convert decimal to octal
hex() - Convert decimal to hexadecimal
2. Mathematical Functions
abs(x) - Absolute value of number, e.g., abs(-10) returns 10
ceil(x) - Ceiling of number, e.g., math.ceil(4.1) returns 5
cmp(x, y) - Returns -1 if x < y, 0 if x == y, 1 if x > y (deprecated in Python 3)
exp(x) - Exponential of x, e.g., math.exp(1) returns 2.718281828459045
fabs(x) - Absolute value as float, e.g., math.fabs(-10) returns 10.0
floor(x) - Floor of number, e.g., math.floor(4.9) returns 4
log(x) - Natural logarithm, e.g., math.log(math.e) returns 1.0
log10(x) - Base-10 logarithm, e.g., math.log10(100) returns 2.0
max(x1, x2,...) - Maximum of given arguments
min(x1, x2,...) - Minimum of given arguments
modf(x) - Integer and fractional parts of x
pow(x, y) - Power operation equivalent to x**y
round(x [,n]) - Round to nearest integer or n decimal places
sqrt(x) - Square root of x
3. Trigonometric Functions
acos(x) - Arc cosine in radians
asin(x) - Arc sine in radians
atan(x) - Arc tangent in radians
atan2(y, x) - Arc tangent of y/x
cos(x) - Cosine of x in radians
hypot(x, y) - Euclidean norm sqrt(x*x + y*y)
sin(x) - Sine of x in radians
tan(x) - Tangent of x in radians
degrees(x) - Convert radians to degrees
radians(x) - Convert degrees to radians
4. Mathematical Constants
pi - Mathematical constant π
e - Mathematical constant e (natural logarithm base)
Strings (str)
Definition: An ordered collection of characters used to store and represent text information. Defined using '', "", or """ """.
String formats: '...', "...", """..."""
Key characteristics:
- Immutable once created
- Modifications or concatenations create new strings
- Indexing starts at 0
- Length calculated with len()
- Slicing works with [start:end] (exclsuive end)
- Support for loops: for character in string
- range() creates sequences of numbers
String Methods:
capitalize() - Capitalize first character
center(width, fillchar) - Center string with specified width and fill character
count(substring, start=0, end=len(string)) - Count occurrences of substring
encode(encoding='UTF-8', errors='strict') - Encode string using specified encoding
endswith(suffix, start=0, end=len(string)) - Check if string ends with suffix
find(substring, start=0, end=len(string)) - Find first occurrence of substring, return -1 if not found
index(substring, start=0, end=len(string)) - Find first occurrence, raise exception if not found
isalnum() - Check if all characters are alphanumeric
isalpha() - Check if all characters are alphabetic
isdigit() - Check if all characters are digits
islower() - Check if all characters are lowercase
isupper() - Check if all characters are uppercase
join(iterable) - Join elements with string as separator
lower() - Convert to lowercase
replace(old, new, count) - Replace occurrences of old with new
split(separator, maxsplit) - Split string into list based on separator
startswith(prefix, start=0, end=len(string)) - Check if string starts with prefix
strip([chars]) - Remove leading/trailing characters
title() - Title case (first letter of each word capitalized)
upper() - Convert to uppercase
zfill(width) - Pad string with zeros to specified width
Lists [list]
Examples: [11,22,33], ['python', 'java']
List Methods
append(item) - Add item to end of list
my_list = [1,3,5,7,9]
my_list.append(4)
print(my_list) # [1,3,5,7,9,4]
clear() - Remove all items from list
my_list = [1,3,5,7,9]
my_list.clear()
print(my_list) # []
copy() - Create shallow copy of list
my_list = [1,3,5,7,9]
copied = my_list.copy()
print(copied)
count(value) - Count occurrences of value
my_list = [1,3,5,7,9,3]
occurrences = my_list.count(3)
print(occurrences) # 2
extend(iterable) - Add all items from iterable to list
my_list = [1,3,5]
my_list.extend([7,9])
print(my_list) # [1,3,5,7,9]
index(value, start=0, end=len(list)) - Find index of first occurrence
my_list = [1,3,5,7,9]
position = my_list.index(5)
print(position) # 2
insert(index, item) - Insert item at specified position
my_list = [1,3,5,7,9]
my_list.insert(2, 4)
print(my_list) # [1,3,4,5,7,9]
pop(index=-1) - Remove and return item at index
my_list = [1,3,5,7,9]
removed = my_list.pop(1)
print(my_list) # [1,5,7,9]
print(removed) # 3
remove(value) - Remove first occurrence of value
my_list = [1,3,5,7,9,3]
my_list.remove(3)
print(my_list) # [1,5,7,9,3]
reverse() - Reverse order of list in place
my_list = [1,3,5,7,9]
my_list.reverse()
print(my_list) # [9,7,5,3,1]
sort(key=None, reverse=False) - Sort list in place
my_list = [9,1,7,3,5]
my_list.sort(reverse=True)
print(my_list) # [9,7,5,3,1]
List Comprehensions
List comprehensions provide a concise way to create lists. Each comprehenison consists of an expression followed by a for clause, then zero or more for or if clauses.
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
# Result: [8, 6, -18, 16, 12, -36, 24, 18, -54]
[x+y for x in vec1 for y in vec2]
# Result: [6, 5, -7, 8, 7, -5, 10, 9, -3]
[vec1[i]*vec2[i] for i in range(len(vec1))]
# Result: [8, 12, -54]
Tuples (tuple)
Tuples are immutable sequences, typicallly used to store heterogeneous data. They are defined with parentheses () and are immutable.
Tuple Operations
Similar to strings, tuples support + and * operators for concatenation and repetition:
print(len((5, 7, 9,))) # Output: 3
(5, 7, 9) + (10, 11, 12) # Result: (5, 7, 9, 10, 11, 12)
('Hello!',) * 3 # Result: ('Hello!', 'Hello!', 'Hello!')
8 in (5, 7, 9) # Result: False
for x in (5, 7, 9): print(x) # Output: 5 7 9
Tuple Methods
len(tuple) - Get length of tuple
max(tuple) - Get maximum value in tuple
min(tuple) - Get minimum value in tuple
tuple(sequence) - Convert sequence to tuple
Dictionaries {dict}
Dictionaries store key-value pairs in curly braces {}. Keys must be immutable, values can be any type.
- Values can be any data type
- Lists and dictionaries cannot be keys
- Unordered collections
- No slicing due to lack of order
- Support deletion and iteration
Dictionary Methods
dict.clear() - Remove all items from dictionary
dict.copy() - Create shallow copy of dictionary
dict.fromkeys(seq, value) - Create new dictionary with keys from seq and value
dict.get(key, default) - Get value for key, return default if key not found
key in dict - Check if key exists in dictionary
dict.items() - Return list of key-value tuple pairs
dict.keys() - Return list of keys
dict.values() - Return list of values
dict.pop(key, default) - Remove key and return its value
dict.update(other_dict) - Update dictionary with key-value pairs from other
Sets (set)
Sets are unordered collections of unique elements. Key characteristics:
- Contain distinct elements
- No duplicate values
- Elements must be immutable types
students = {'Alice', 'Bob', 'Charlie', 'Alice', 'David', 'Eve'}
print(students) # Duplicates automatically removed
# Membership testing
if('Eve' in students):
print('Eve exists in set')
else:
print('Eve does not exist in set')
# Set operations
a = set('hello')
b = set('world')
print(a - b) # Difference
print(a | b) # Union
print(a & b) # Intersection
print(a ^ b) # Symmetric difference
Set Methods
add() - Add element to set
my_set = {1,2,5,5,'x','y'}
my_set.add(3)
print(my_set) # {1, 2, 3, 5, 'y', 'x'}
clear() - Remove all elements from set
intersection() - Find common elements (equivalent to &)
set_a = {1,7,9}
set_b = {1,9,5}
print(set_a & set_b) # {9, 1}
print(set_a.intersection(set_b)) # {9, 1}
union() - Combine sets (equivalent to |)
set_a = {1,7,9}
set_b = {1,9,5}
print(set_a | set_b) # {1, 5, 7, 9}
print(set_a.union(set_b)) # {1, 5, 7, 9}
difference() - Elements in first set but not second (equivalent to -)
set_a = {1,7,9}
set_b = {1,9,5}
print(set_a - set_b) # {7}
print(set_a.difference(set_b)) # {7}
symmetric_difference() - Elements in either set but not both (equivalent to ^)
set_a = {1,7,9}
set_b = {1,9,5}
print(set_a ^ set_b) # {5, 7}
print(set_a.symmetric_difference(set_b)) # {5, 7}
issubset() - Check if one set is subset of another
small_set = {1,2}
large_set = {1,2,3}
print(small_set.issubset(large_set)) # True
print(large_set.issubset(small_set)) # False
issuperset() - Check if one set is superset of another
small_set = {1,2}
large_set = {1,2,3}
print(large_set.issuperset(small_set)) # True
pop(), remove(), discard() - Different ways to remove elements
my_set = {9, 'item', 1, 2, 3, 4, 5, 6}
my_set.pop() # Randomly removes element
my_set = {9, 'item', 1, 2, 3, 4, 5, 6}
my_set.remove(4) # Removes specific element, raises error if not found
my_set = {9, 'item', 1, 2, 3, 4, 5, 6}
my_set.discard(5) # Removes specific element, no error if not found