Podcast
Questions and Answers
Which of the following best describes a Python list?
Which of the following best describes a Python list?
- A mutable sequence of elements. (correct)
- A data type that can only hold integers.
- A data type that cannot be indexed.
- An immutable sequence of elements.
What symbols are used to enclose the elements of a list?
What symbols are used to enclose the elements of a list?
- Curly Braces {}
- Parentheses ()
- Angle Brackets <>
- Square Brackets [] (correct)
Which characteristic is associated with Python lists?
Which characteristic is associated with Python lists?
- Duplicate objects are not allowed.
- Insertion order is not preserved.
- Insertion order is preserved. (correct)
- Elements must be of the same data type.
What does it mean for a Python list to be 'mutable'?
What does it mean for a Python list to be 'mutable'?
What does the term 'heterogeneous objects' refer to in the context of Python lists?
What does the term 'heterogeneous objects' refer to in the context of Python lists?
In Python, what does a positive index in a list indicate?
In Python, what does a positive index in a list indicate?
How are elements separated when creating a list?
How are elements separated when creating a list?
How do you create an empty list in Python?
How do you create an empty list in Python?
What is the index range of a list?
What is the index range of a list?
What is the purpose of the slice operator in Python lists?
What is the purpose of the slice operator in Python lists?
Which list method adds an element to the end of a list?
Which list method adds an element to the end of a list?
Which list method adds multiple elements to the end of a list?
Which list method adds multiple elements to the end of a list?
Which list method inserts an element at a specific index?
Which list method inserts an element at a specific index?
How do you modify an element at a specific index in a list?
How do you modify an element at a specific index in a list?
Which keyword is used to delete an element at a specific index in a list?
Which keyword is used to delete an element at a specific index in a list?
Which list method removes the first occurrence of a specific element?
Which list method removes the first occurrence of a specific element?
Which list method removes an element at a specified index and returns it?
Which list method removes an element at a specified index and returns it?
Which list method removes all elements from the list?
Which list method removes all elements from the list?
What does the sort()
method do to a list?
What does the sort()
method do to a list?
What does the sorted()
function do to a list?
What does the sorted()
function do to a list?
How can you sort a list in descending order using the sort()
method?
How can you sort a list in descending order using the sort()
method?
Which list method returns the index of the first occurrence of a value?
Which list method returns the index of the first occurrence of a value?
Which list method returns the number of occurrences of a value?
Which list method returns the number of occurrences of a value?
Which list method reverses the order of elements in the list?
Which list method reverses the order of elements in the list?
What does the * operator do when used with lists?
What does the * operator do when used with lists?
What does the len()
function return when used with lists?
What does the len()
function return when used with lists?
What is the purpose of list comprehension?
What is the purpose of list comprehension?
What is a nested list?
What is a nested list?
How do you access elements in a nested list?
How do you access elements in a nested list?
Are tuples mutable?
Are tuples mutable?
What type of brackets are used to define a tuple?
What type of brackets are used to define a tuple?
If t = (1, 2, 3)
, what will print(t[0])
output?
If t = (1, 2, 3)
, what will print(t[0])
output?
How can you create a tuple with a single element?
How can you create a tuple with a single element?
Which of the these statements are applicable to tuples?
Which of the these statements are applicable to tuples?
Can you remove elements from a tuple after it is created?
Can you remove elements from a tuple after it is created?
How can you delete an entire tuple?
How can you delete an entire tuple?
What function is used to find the number of items in a tuple?
What function is used to find the number of items in a tuple?
Which function converts a list into a tuple?
Which function converts a list into a tuple?
How do you access the last element of a tuple?
How do you access the last element of a tuple?
Which of the following best describes a Python string?
Which of the following best describes a Python string?
Which of the following ways are accepted when assigning a string to a variable?
Which of the following ways are accepted when assigning a string to a variable?
What is string concatenation?
What is string concatenation?
How do you concatenate strings in Python?
How do you concatenate strings in Python?
How can you repeat a string multiple times?
How can you repeat a string multiple times?
Which string method converts a string to lowercase?
Which string method converts a string to lowercase?
Flashcards
Python List
Python List
A mutable, ordered collection of items that can store different data types.
Creating a List
Creating a List
Placing elements inside square brackets [] and separating them with commas.
List Indexing
List Indexing
Accessing elements of a list using their position number.
List Slicing
List Slicing
Signup and view all the flashcards
List append()
List append()
Signup and view all the flashcards
List extend()
List extend()
Signup and view all the flashcards
List insert()
List insert()
Signup and view all the flashcards
Updating List Elements
Updating List Elements
Signup and view all the flashcards
List del
List del
Signup and view all the flashcards
List remove()
List remove()
Signup and view all the flashcards
List pop()
List pop()
Signup and view all the flashcards
List clear()
List clear()
Signup and view all the flashcards
List sort()
List sort()
Signup and view all the flashcards
List index()
List index()
Signup and view all the flashcards
List count()
List count()
Signup and view all the flashcards
List reverse()
List reverse()
Signup and view all the flashcards
List Repetition
List Repetition
Signup and view all the flashcards
List Concatenation
List Concatenation
Signup and view all the flashcards
List len()
List len()
Signup and view all the flashcards
List Iteration
List Iteration
Signup and view all the flashcards
List Membership
List Membership
Signup and view all the flashcards
List max()
List max()
Signup and view all the flashcards
List min()
List min()
Signup and view all the flashcards
List Comprehension
List Comprehension
Signup and view all the flashcards
Nested List
Nested List
Signup and view all the flashcards
Size of Nested List
Size of Nested List
Signup and view all the flashcards
Tuple
Tuple
Signup and view all the flashcards
Creating a Tuple
Creating a Tuple
Signup and view all the flashcards
Accessing Tuple Elements
Accessing Tuple Elements
Signup and view all the flashcards
Tuple Traversal
Tuple Traversal
Signup and view all the flashcards
Slicing Tuples
Slicing Tuples
Signup and view all the flashcards
Searching Tuples
Searching Tuples
Signup and view all the flashcards
Length of Tuple
Length of Tuple
Signup and view all the flashcards
List to Tuple
List to Tuple
Signup and view all the flashcards
Built-in Tuple Methods
Built-in Tuple Methods
Signup and view all the flashcards
re module
re module
Signup and view all the flashcards
Quantifiers
Quantifiers
Signup and view all the flashcards
dict
dict
Signup and view all the flashcards
Modify Dictionnary
Modify Dictionnary
Signup and view all the flashcards
keys:
keys:
Signup and view all the flashcards
Study Notes
- Module 3 covers Sequences, Sets, Dictionaries, and Regular Expressions in Python.
Python Lists
- Lists store sequences of various data types and are collections of different kinds of values.
- Lists are mutable, allowing changes to their elements after creation.
- Commas and square brackets separate and enclose list items.
Characteristics of Lists
- Lists represent a group of individual objects as a single entity.
- List elements are enclosed in square brackets and separated by commas e.g.,
a=[34,22,65,11]
. - Lists preserve insertion order.
- Duplicate objects Lists allow duplicate objects.
Heterogeneous Lists
- Lists can contain heterogeneous objects, example:
a.append('python')
, adding a string to a list of numbers. - Lists are dynamic, which means that their size can increase or decrease.
- Positive and negative indexing is allowed allowing access from left-to-right or right-to-left.
- List objects are mutable, meaning their content can change.
Creating a List
- Lists can be created by placing elements inside square brackets and separating them with commas e.g.,
list1 = [1, 2, "Python", "Program", 15.9]
.
List Indexing and Splitting
- List indexing operates similarly to string processing, utilizing the slice operator
[]
. - Indexes range from 0 to the list's length minus 1.
- The 0th index stores the first element, the 1st index stores the second element, and so on.
- With
list_variable(start: stop: step)
, specify a sub-list, where "start" is the beginning record position, "stop" is the last record position and "step" skips elements in between
Negative Indexing
- Python supports negative indexing, counting from the right.
-1
represents the last element,-2
the second-to-last, and so on.
Inserting Elements into a List
append()
adds an element to the end of the list.extend()
adds multiple elements to the end of the list.insert()
adds an element at a specific position.
Updating Elements in a List
- List mutability means elements at specific indexes can be changed by assigning a new value to that index.
- Multiple elements can also be updated using slicing.
Deleting Elements from a List
del
deletes an element at a specified index.remove()
removes the first occurrence of a specific element.pop()
removes and returns the element at a specified index, defaulting to the last element.clear()
removes all elements from the list.remove()
is used to remove a specified item
Sorting Elements of a List
- Lists are sorted using
sort()
(modifies the original list) orsorted()
(returns a new sorted list). - Both functions support ascending or descending order and custom sorting criteria via the
key
argument. sort()
sorts alphanumerically, ascending, by default and is case-sensitive, sorting uppercase letters before lowercase.- To sort descending, use the keyword argument
reverse = True
.
Additional Methods
index()
returns the index of the first occurrence of a value.count()
returns the number of occurrences of a value.reverse()
reverses the order of elements in the list.
List Operations
- Concatenation (
+
) and repetition (*
) work similarly to strings. - Additional list operations include: repetition, concatenation, length, iteration, and membership.
- Repetition empowers the rundown components to be rehashed on different occasions
List Functions
len()
calculates the length of the list.max()
returns the maximum element of the list.min()
returns the minimum element of the list.
List Comprehension
- List comprehension offers a shorter way to create new lists based on existing list values.
- For example, create a new list containing only the fruits with the letter ‘a’ in the name e.g.,
newlist = [x for x in fruits if "a" in x]
List Comprehension Syntax
[expression for item in iterable if condition]
expression
is the transformation or value to be included in the new list.item
is the current element from the iterable.iterable
is a sequence or collection (e.g., list, tuple, set).if condition
is an optional filtering condition that decides whether the current item should be included.
List Comprehension Examples
- A simple list comprehension to create a list of squares of numbers: squares =
[x ** 2 for x in range(5)]
, the output is[0, 1, 4, 9, 16]
- Apply string operations using list comprehensions words =
["hello", "world", "python", "is", "great"]
lengths =[len(word) for word in words]
, the output is[5, 5, 6, 2, 5]
- Add a condition even_numbers =
[x for x in range(10) if x % 2 == 0]
, the output is[0, 2, 4, 6, 8]
and apply functions or methods: upper_words =[word.upper() for word in words]
, the output is['HELLO', 'WORLD', 'PYTHON']
- Create another list comprehension:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
andflattened = [item for row in matrix for item in row]
, the output is[1, 2, 3, 4, 5, 6, 7, 8, 9]
Advantages of List Comprehensions
- They are concise and readable, creating lists in a single line.
- Offer faster execution due to internal optimizations in Python.
- This supports the functional programming paradigm..
Nested Lists
- A nested list in Python is a list that contains other lists as its elements, creating a multi-dimensional array-like structure.
- Nested lists are useful for matrices, grids, or any hierarchically structured data.
Creating Nested Lists
- Create a nested list by including lists inside another list e.g.,
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Lists can be arbitrarily nested.
- Nested lists can be of different sizes and dimensions.
Accessing Elements in Nested Lists
- Use multiple indices to access elements, where the first index refers to the outer list, and the second (or further) refers to the inner lists.
- Update a single element e.g.,
nested_list[1][0] = 10
or update a sublistnested_list[1] = ['a', 'b', 'c']
.
Iterating Over Nested Lists
- Loop through nested lists using nested loops.
- You can also use list comprehensions for flattening or extracting elements from nested lists.
Common Use Cases of Nested Lists
- Represent matrices and grids (2D grids).
- They can be used to represent more complex structures, such as multi-level categories or hierarchical data.
Common Operations on Nested Lists
- Use
len()
to get the number of sublists. - Access all elements via list comprehension e.g.,
all_elements = [item for sublist in nested_list for item in sublist]
. - Transposing a matrix means swapping rows with columns using list comprehension or built-in functions like
zip()
. - check if an element exists using a loop or conditional logic.
Multi-level Nested Lists
- Extends beyond two levels to create multi-dimensional data structures.
Tuples in Python
- Tuples are immutable, ordered collections of items, defined using parentheses and can store items of any data type.
- Tuples prevent data modification during program execution.
Characteristics of Tuples
- Similar to lists, tuples are ordered and elements are accessed using index values.
- Items are immutable.
- tuples cannot be appended, extended, or removed.
Creating Tuples
- Create tuples by placing comma-separated values inside parentheses e.g.,
t = (10, 20, 30)
. - Parentheses are not strictly required when defining a tuple with a single element, but a trailing comma is required e.g.,
single_element_tuple = (10,)
. - Tuples can be created without parentheses.
- Data types can be mixed e.g.,
mixed_tuple = (1, "hello", 3.14, True)
.
Accessing Tuple Elements
- Tuples support indexing from 0, and also negative indexing.
- They can be accessed using positive or negative indexing or you can use slice
print(t[2:5])
or a while loop, or a for loop,
Traversing Items
- You can also traverse a tuple using a for loop.
Slicing Tuples
- Slicing divides a tuple into smaller tuples using the indexing method e.g.,
(0,1, 2, 3) t[1:]
- The sliced tuple can include reverse indexing print(t[::-1])
- Or elements from index 2 to 4
print(t[2:4])
Searching Elements in a Tuple
- Search for elements even though tuples are immutable with in and index().
- This in example checks for element existence in a tuple e.g.,
print(3 in my_tuple)
. - The index() example checks element position e.g.,
print(my_tuple.index(30))
.
Modifying a Tuple
- You can create a new tuple by concatenating existing elements e.g.,
(my_tuple[:1] + (4,) + my_tuple[2:])
Deleting a Tuple
- In Python, to delete a tuple, use the del keyword.
- After deleting the tuple, you will get a 'NameError' if you try to access it.
- It's no possible to remove individual elements only the whole tuple.
Finding Tuple Length
- Python's len() function retrieves the length of a tuple.
Multiple Data Types
- Tuples support elements with multiple data types.
Sorting
- Tuples lack a sort() method due to immutability.
- You can use Python's built-in sorted() function to sort.
Nested Tuples
- Can contain other tuples to create multi-dimensional structures.
Tuple Operations
- You cane concatenate and repeat tuples.
Converting Lists
- Can convert a list to a tuple using tuple().
Tuple Methods
- While tuples are immutable and lack list-like methods, they include built-in methods.
count(x)
returns occurrences.index(x)
returns the index.
Strings in Python
- Strings are collections of characters surrounded by single, double, or triple quotes.
Creating Strings
- Strings are created by enclosing characters in single or double quotes, but triple quotes are generally used for multiline strings or docstrings.
String indexing and splitting
- Indexing strings follows the same logic as indexing other data structures in Python e.g.,
str[0] = 'H'
. - You can slice a string into smaller parts e.g.,
str[2:4] # prints II
String Operations
- Concatenation combines strings using the
+
operator. - Repetition repeats a string multiple times using the
*
operator. - Indexing accesses characters using their index starting from 0
- Slicing extracts a substring using
str[start:end]
. - To get the number of characters in a string use
len()
. - To check whether a substring exists, use in or not in
String Formatting
- Python's escape sequences, denoted by a backslash, handle special characters within strings.
- Common escape sequences include
\newline
,\\
,\'
,\"
,\a
,\b
,\f
,\n
,\r
,\t
,\v
. - The format() method uses curly braces as placeholders to insert values and the operator
%
binds values with format specifiers
String Handling Methods
- to lowercase:
lower()
- to uppercase:
upper()
- Capatalizes the first letter
capitalize()
- Capitalizes first letter of each word in the string
title()
- Removes leading or trailing white space
strip()
- Replaces a substring
replace()
- Finds a substring
find()
- Splits strings into a list based on default white space
split()
- It joins strings with a specified parameter
join()
- Checks if string starts or ends with these characters
startswith()
andendswith()
Sets In Python
- Sets are unordered collections of unique elements, commonly used to store multiple items without specific order.
Sets Characteristics
- Each element in a set is unique and can be of any immutable data type.
- Sets are mutable, allowing addition or removal of elements in Python.
- Duplicates are not allowed but heteroegenous elements are
- Mathematical operations like Union, Intersection, Difference can be appleid.
Set Creation
- Sets can be created by curly braces e.g.,
my_set = {1, 2, 3, 4, 5}
. - Sets can be created by a
set()
constuctor e.g.,my_set = set([1, 2, 3, 4, 5])
. - You can create an empty set with the
set()
constuctor e.g.,empty_set = set()
Adding Elements
- Adds a single element with the add() methos e.g,.
my_set.add(4)
.
Removing Elements
- Removes a specific elmement with the remove() method
- The discard() method removes an element if exist but wont raise an error if the element cant be found
- pop() removes or returns an arbotrary element from the list.
- clear removes all elements
Set Operations
- Python allows several mathematical operations on sets: -Union | or union() -Intersection & or intersection() -Difference () or difference() -Symmetric Difference or symmetric_difference():
Subset and Superset
- the issubset() methods checks where the subsets and supersets are available.
- isdisjoint() checks if two sets have nothign in common
Set Comprehension
- Set comprehension is similar to list comprehension. It's a concise way to create sets by applying expressions to iterate over an iterable e.g.,
my_set = {x for x in range(1, 6) if x % 2 == 0}
Dictionaries in Python
- Dictionaries are unordered collections of key-value pairs, each key must be unique value can be of any data type, and dictionaries are mutable.
Creating a Dictionary
- Use curly braces
{}
,my_dict = {"name": "Alice", "age": 25, "city": "New York"}
- You can use the
dict()
constructor, by passing the key and values,my_dict = dict(name="Alice", age=25, city="New York")
- A list of tuples
my_dict = dict([("name", "Alice"), ("age", 25), ("city", "New York")])
Operations on Dictionaries
- Use square brackets
name = my_dict["name"]
or functions to access an object - For operations like adding, assigning key values, removing key values e.g., assigning key values
my_dict["address"] = "123 Main St"
- Use del to remeove a value from a dict key e.g.,
del my_dict["address"]
- Use functions like
pop()
andclear()
Dictionary Methods
keys()
returns a view of all keys.values()
returns a view of all values.items()
returns a view of all key-value pairs.update()
merges elements from another dictionary e.g.,new_data
or with key-value pairs.setdefault()
adds a key with a default value if it doesn't exist.fromkeys()
creates another dictionary with some values
Sorting
- Dictionaries can be sorted by keys or by values with a lambda expression
Regular Expressions in Python
- Regex are powerful tools used for pattern matching and searching within strings and the re module in Python is used for regular expressions in text processing tasks like validating input.
Regular Expression Operations
- Define operations using a re module
- Set
import re
to import modules - The syntax follows using
r
which follows basic special characters to find and match texts
Regex Functions
findall
Returns a list containing all matchessearch
Returns a Match object if there is a match anywhere in the stringsplit
Returns a list where the string has been split at each matchsub
Replaces one or many matches with a string
Sequence Characters
- Sequence characters form simple patterns to match parts of text.
- Literal characters simply find exact characters
- The dot matches anything except new lines
- ^Caret finds the beginning of a string
- $ Dollar Sign finds the end of a string
- And [] specifies type of character
Quantifiers
- Quantifiers define the repetition of patterns
-
- Asterisk: Matches zero or more occurrences
-
- Plus: Matches one or more occurrences
- ? Question Mark: Matches zero or one occurrence
- {n,m}: Matches a specified range of occurrences
Special Character sets
- \ Backslash is used to escape special characters
- . The dot matches any character except new lines
- Common character classes include \d, \w, \s
- ^or $ are Anchors. Use
re.search()
- Use parantheses to group elements ()
- Use pipes to add alternates to items
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.