Data Types
In Python, data types categorize the types of values that variables can hold. They define how the values can be stored, manipulated, and operated upon in a program. Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable; the interpreter determines it based on the assigned value.
Common data types include integers, floating-point numbers, strings, lists, tuples, dictionaries, sets
Numeric Types
Numeric types in Python represent numerical values and are essential for performing mathematical operations. The main numeric types are int (integer), float (floating-point), and complex (complex numbers).
Integer
Represents whole numbers without any decimal points.
Can be positive or negative.
Pythonnum_int = 42
negative_int = -10
Floating-Point
Represents numbers with decimal points or in exponential form.
Can be used to represent real numbers.
Pythonnum_float = 3.14
Complex Numbers
Represents numbers in the form of a + bj, where "a" and "b" are real numbers, and "j" is the imaginary unit.
Useful in mathematical and engineering applications.
Pythonnum_complex = 2 + 3j
Operations on Numeric Types
Python supports various arithmetic operations on numeric types:
Python# Examples:
a = 10
b = 3
# Addition
sum_result = a + b # Result: 13
# Subtraction
diff_result = a - b # Result: 7
# Multiplication
prod_result = a * b # Result: 30
# Division
div_result = a / b # Result: 3.3333 (floating-point division)
# Floor Division (returns the floor value)
floor_div_result = a // b # Result: 3
# Modulus (returns the remainder)
mod_result = a % b # Result: 1
# Exponentiation
exp_result = a ** b # Result: 1000
String
Strings are sequences of characters, and they can be defined using either single quotes (') or double quotes (").
Strings are immutable, meaning you cannot change the characters of an existing string directly.
Pythonmy_string = "Hello, Python!"
Accessing Characters
You can access individual characters in a string using indexing.
Pythonmy_string = "Hello, Python!"
first_char = my_string[0] # Result: 'H'
String Slicing
Slicing allows you to extract a portion of the string.
Python# Initial string
my_string = "Python Programming"
# String Slicing
substring_1 = my_string[0:6] # Result: 'Python'
substring_2 = my_string[7:18] # Result: 'Programming'
substring_3 = my_string[:6] # Result: 'Python' (omitting start index defaults to 0)
substring_4 = my_string[7:] # Result: 'Programming' (omitting end index defaults to the end)
# Slicing with a step
substring_5 = my_string[0:10:2] # Result: 'Pto rg' (every second character from index 0 to 9)
# Reverse the string using slicing
reversed_string = my_string[::-1] # Result: 'gnimmargorP nohtyP'
Useful String Methods
len() - returns the length (number of characters) of a string.
Pythonmy_string = "Hello, Python!"
length = len(my_string) # Result: 13
lower() and upper() - converts all characters in a string to lowercase and uppercase appropriately
Pythonmy_string = "Hello, Python!"
lowercase_str = my_string.lower() # Result: 'hello, python!'
uppercase_str = my_string.upper() # Result: 'HELLO, PYTHON!'
strip() - removes leading and trailing whitespaces from a string.
lstrip() - removes leading whitespaces.
rstrip() - removes trailing whitespaces
Pythonpadded_str = " Python "
stripped_str = padded_str.strip() # Result: 'Python'
replace() - replaces a specified substring with another substring.
Pythonmy_string = "Hello, Python!"
new_str = my_string.replace("Python", "World") # Result: 'Hello, World!'
find() - returns the index of the first occurrence of a substring (or -1 if not found).
count() - returns the number of occurrences of a substring.
Pythonmy_string = "Hello, Python!"
index = my_string.find("Python") # Result: 7
occurrences = my_string.count("o") # Result: 2
split() - splits a string into a list of substrings based on a specified delimiter.
Pythonmy_string = "Hello, Python!"
words = my_string.split(",") # Result: ['Hello', ' Python!']
join() - joins elements of a sequence (like a list) into a string using the specified separator.
Pythonword_list = ["Hello", "Python!"]
joined_str = ",".join(word_list) # Result: 'Hello,Python!'
startswith() and endswith() - checks if a string starts or ends with a specified substring.
Pythonmy_string = "Hello, Python!"
starts_with = my_string.startswith("Hello") # Result: True
ends_with = my_string.endswith("Python") # Result: False
Check the entire list of strings' methods
String Format
The most common and versatile method for string formatting is using f-strings.
An f-string is created by prefixing a string with the letter "f"
You can embed expressions inside curly braces {} within the string.
Pythonname = "Alice"
age = 30
formatted_str = f"My name is {name} and I am {age} years old."
You can include variables, expressions, and even function calls inside curly braces.
Pythonx = 5
y = 10
result_str = f"The sum of {x} and {y} is {x + y}."
List
Lists are ordered, mutable sequences used to store collections of items. They are defined using square brackets.
Pythonmy_list = [1, 2, 3, "apple", "orange"]
Access List Items
You can access individual items in a list using indexing.
Pythonmy_list = [1, 2, 3, "apple", "orange"]
# Access the first item
first_item = my_list[0] # Result: 1
# Access the third item
third_item = my_list[2] # Result: 3
# Access the last item
last_item = my_list[-1] # Result: 'orange'
# Access a range of items
subset = my_list[1:4] # Result: [2, 3, 'apple']
Change List Items
You can change the value of a specific item in a list using indexing.
Pythonmy_list = [1, 2, 3, "apple", "orange"]
my_list[3] = "banana"
# Result: [1, 2, 3, "banana", "orange"]
Loop Lists
You can iterate through a list using a for loop.
Pythonmy_list = [1, 2, 3, 4]
for item in my_list:
print(item)
# Output: 1
# 2
# 3
# 4
List Comprehension
List comprehension is a concise way to create lists.
Pythonnumbers = [1, 2, 3, 4]
squared_numbers = [x**2 for x in numbers]
# Result: [1, 4, 9, 16]
Join Lists
You can concatenate two lists using the + operator.
Pythonlist1 = [1, 2, 3]
list2 = [4, 5, 6]
joined_list = list1 + list2
# Result: [1, 2, 3, 4, 5, 6]
List Methods
append() - adds an element to the end of the list.
Pythonmy_list = [1, 2, 3]
my_list.append(4)
# Result: [1, 2, 3, 4]
remove() - removes the first occurrence of a specified element from the list.
Pythonmy_list = [1, 2, 3, 4]
my_list.remove(3)
# Result: [1, 2, 4]
pop() - removes and returns the last element from the list (or a specified index).
Pythonmy_list = [1, 2, 3, 4]
last_element = my_list.pop()
# Result: [1, 2, 3], last_element: 4
second_element = my_list.pop(1) # 1 is index of second element
# Result: [1, 3], last_element: 2
insert() - inserts an element at a specified position in the list.
Pythonmy_list = [1, 2, 3]
my_list.insert(1, 4) # 1 is index the position and 4 is the value that will be inserted
# Result: [1, 4, 2, 3]
sort() - sorts the elements of the list in ascending order.
Pythonmy_list = [3, 1, 4, 1, 5, 9, 2]
my_list.sort()
# Result: [1, 1, 2, 3, 4, 5, 9]
reverse() - reverses the order of the elements in the list.
Pythonmy_list = [1, 2, 3, 4]
my_list.reverse()
# Result: [4, 3, 2, 1]
count() - returns the number of occurrences of a specified element in the list.
Pythonmy_list = [1, 2, 2, 3, 4, 2, 5]
count_of_2 = my_list.count(2)
# Result: 3
extend() - extends the list by appending elements from another list.
Pythonlist1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
# Result: [1, 2, 3, 4, 5, 6]
index() - returns the index of the first occurrence of a specified element in the list (or raises a ValueError if not found).
Pythonmy_list = [1, 2, 3, 4]
index_of_3 = my_list.index(3)
# Result: 2
Tuple
Tuples are ordered, immutable sequences used to store collections of items. They are defined using parentheses.
Pythonmy_tuple = (1, 2, 3, "apple", "orange")
Access Tuple Items
You can access individual items in a tuple using indexing (like a list).
Pythonmy_tuple = (1, 2, 3, "apple", "orange")
first_item = my_tuple[0] # Result: 1
Update Tuples
Tuples are immutable, meaning you cannot change the values of items once they are set.
Pythonoriginal_tuple = (1, 2, 3)
new_tuple = original_tuple + (4, 5)
# Result: (1, 2, 3, 4, 5)
Unpack Tuples
You can assign the elements of a tuple to individual variables using unpacking (list has the same behavior).
Pythonmy_tuple = (1, 2, 3)
a, b, c = my_tuple
# Variables: a=1, b=2, c=3
Loop Tuples
You can iterate through a tuple using a for loop.
Pythonmy_tuple = (1, 2, 3, 4)
for item in my_tuple:
print(item)
# Output: 1
# 2
# 3
# 4
Join Tuples
You can concatenate two tuples using the + operator.
Pythontuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
joined_tuple = tuple1 + tuple2
# Result: (1, 2, 3, 4, 5, 6)
Tuple Methods
count() - returns the number of occurrences of a specified element in the tuple.
Pythonmy_tuple = (1, 2, 2, 3, 4, 2, 5)
count_of_2 = my_tuple.count(2)
# Result: 3
index() - returns the index of the first occurrence of a specified element in the tuple (or raises a ValueError if not found).
Pythonmy_tuple = (1, 2, 3, 4)
index_of_3 = my_tuple.index(3)
# Result: 2
Dictionary
Dictionaries are unordered, mutable collections of items. They are defined using curly braces and consist of key-value pairs.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
Accessing Dictionary Items
You can access the value associated with a specific key in a dictionary.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
name_value = my_dict["name"] # Result: "John"
Change Dictionary Items
You can change the value associated with a specific key in a dictionary.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict["age"] = 31
# Result: {"name": "John", "age": 31, "city": "New York"}
Add Dictionary Items
You can add new key-value pairs to a dictionary.
Pythonmy_dict = {"name": "John", "age": 30}
my_dict["city"] = "New York"
# Result: {"name": "John", "age": 30, "city": "New York"}
Nested Dictionaries
Dictionaries can be nested inside other dictionaries.
Pythonnested_dict = {"person": {"name": "John", "age": 30, "city": "New York"}}
# Accessing nested value: nested_dict["person"]["age"]
Dictionary Methods
keys() - returns a list of all the keys in the dictionary.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
keys_view = my_dict.keys()
# Result: dict_keys(['name', 'age', 'city'])
values() - returns a list of all the values in the dictionary.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
values_view = my_dict.values()
# Result: dict_values(['John', 30, 'New York'])
items() - returns a list of all key-value pairs in the dictionary.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
items_view = my_dict.items()
# Result: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
get() - returns the value for the specified key. If the key is not found, it returns a default value.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
age_value = my_dict.get("age", 0) # 0 is default value
# Result: 30
# Alternatively: age_value = my_dict["age"] if "age" in my_dict else 0
pop() - removes the item with the specified key and returns its value.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
age_value = my_dict.pop("age")
# Result: age_value: 30, my_dict: {'name': 'John', 'city': 'New York'}
popitem() - removes and returns the last inserted key-value pair.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
last_item = my_dict.popitem()
# Result: last_item: ('city', 'New York'), my_dict: {'name': 'John', 'age': 30}
update() - updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.
Pythonmy_dict = {"name": "John", "age": 30}
new_data = {"city": "New York", "gender": "Male"}
my_dict.update(new_data)
# Result: {'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'Male'}
clear() - removes all items from the dictionary.
Pythonmy_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict.clear()
# Result: {}
Set
Sets are unordered, mutable collections of unique items. They are defined using curly braces.
Pythonmy_set = {1, 1, 2, 2, 3, 4, 5}
# Notice set doesn't have any duplicate items
# Result: {1, 2, 3, 4, 5}
Access Set Items
You can access items in a set, but sets are unordered, so there is no index. You can check for membership.
Pythonmy_set = {1, 2, 3, 4, 5}
is_present = 3 in my_set # Result: True
Loop Sets
You can iterate through a set using a for loop.
Pythonmy_set = {1, 2, 3, 4}
for item in my_set:
print(item)
# Output: 1
# 2
# 3
# 4
Set Methods
add() - adds an element to the set.
Pythonmy_set = {1, 2, 3}
my_set.add(4)
# Result: {1, 2, 3, 4}
remove() - removes the specified element from the set.
Pythonmy_set = {1, 2, 3, 4}
my_set.remove(3)
# Result: {1, 2, 4}
discard() - removes the specified element from the set if present.
Pythonmy_set = {1, 2, 3, 4}
my_set.discard(2)
# Result: {1, 3, 4}
union() - returns a new set containing the union of sets.
Pythonset1 = {1, 2, 3}
set2 = {3, 4, 5}
joined_set = set1.union(set2)
# Result: {1, 2, 3, 4, 5}
| - returns a new set containing the union of sets using the | operator.
Pythonset1 = {1, 2, 3}
set2 = {3, 4, 5}
joined_set = set1 | set2
# Result: {1, 2, 3, 4, 5}
difference() - returns a new set containing the difference between two or more sets.
Pythonset1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
diff_set = set1.difference(set2)
# Result: {1, 2}
- - returns a new set containing the difference between sets using the - operator.
Pythonset1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
diff_set = set1 - set2
# Result: {1, 2}
intersection() - returns a new set containing the intersection of two or more sets.
Pythonset1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
# Result: {3, 4}
& - returns a new set containing the intersection of sets using the & operator.
Pythonset1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
intersection_set = set1 & set2
# Result: {3, 4}
Boolean
Boolean Values
Boolean values in Python are True and False.
Pythonmy_boolean = True
another_boolean = False
Evaluate Values and Variables
Values and variables can be evaluated in Boolean context, resulting in either True or False.
Pythonx = 5
y = 10
is_greater = x > y # Result: False
Most Values are True
In a Boolean context, most values are considered True. Examples include non-zero numbers, non-empty strings, and non-empty lists.
Pythonvalue = 42
is_true = bool(value) # Result: True
Some Values are False
Some values are considered False in a Boolean context. Examples include zero, empty strings, and empty lists.
Pythonempty_list = []
is_false = bool(empty_list) # Result: False
Functions can Return a Boolean
Functions can return Boolean values, allowing for conditional checks based on their results.
Pythondef is_even(number):
return number % 2 == 0
result = is_even(4) # Result: True
Python NoneType
In Python, None is a special constant representing the absence of a value or a null value. It is often used to signify that a variable or a function does not have a meaningful value or result.
Assignment of None
Pythonmy_variable = None
Function Return Values
Functions in Python can explicitly return None to indicate that they don't produce any meaningful result.
Pythondef do_something():
# code to do something
return None
Default Function Arguments
None is commonly used as a default value for function parameters when the absence of a user-provided value is meaningful.
Pythondef greet(name=None):
if name is None:
print("Hello, anonymous!")
else:
print(f"Hello, {name}!")
greet() # Output: Hello, anonymous!
greet("John") # Output: Hello, John!
Checking for None
You can check if a variable is None using the is operator.
Pythonif some_variable is None:
print("The variable is None.")
else:
print("The variable has a value.")
Comparisons
None is considered equal to itself and evaluates to False in a boolean context.
Pythonx = None
y = None
print(x == y) # Output: True
print(bool(None)) # Output: False