Contents:
- Loops:
while loops
Syntax:
while specified condition is True:
body of loop
for loops
Syntax:
for variable in sequence:
body of loop
Importance of 'for' in lists in Python
sequence = range(10)
new_list = []
for x in sequence:
if x % 2 == 0:
new_list.append(x)
Can be written as follows in short:
sequence = range(10)
new_list = [x for x in sequence if x % 2 == 0]
Strings:
String Operations and Methods
.format() - String method that can be used to concatenate and format strings.
- {:.2f} - Within the .format() method, limits a floating point variable to 2 decimal places. The number of decimal places can be customized.
len(string) - String operation that returns the length of the string.
string[x] - String operation that accesses the character at index [x] of the string, where indexing starts at zero.
string[x:y] - String operation that accesses a substring starting at index [x] and ending at index [y-1]. If x is omitted, its value defaults to 0. If y is omitted, the value will default to len(string).
string.replace(old, new) - String method that returns a new string where all occurrences of an old substring have been replaced by a new substring.
string.lower() - String method that returns a copy of the string with all lowercase characters.
if character.isalpha(): # The if-statement checks if the character is not a space.
Lists:
Lists and tuples are both sequences and they share a number of sequence operations. The following common sequence operations are used by both lists and tuples:
len(sequence) - Returns the length of the sequence.
for element in sequence - Iterates over each element in the sequence.
if element in sequence - Checks whether the element is part of the sequence.
sequence[x] - Accesses the element at index [x] of the sequence, starting at zero
sequence[x:y] - Accesses a slice starting at index [x], ending at index [y-1]. If [x] is omitted, the index will start at 0 by default. If [y] is omitted, the len(sequence) will set the ending index position by default.
for index, element in enumerate(sequence) - Iterates over both the indices and the elements in the sequence at the same time.
Because integers are not iterable, they need to be converted to a range as such:
for x in range(len(someList)):
print(x)
# this will print out a numerical value up to the length of the original string
Slicing is a way to get a subset (a smaller part) of a list or string in Python. It's like cutting a piece of cake from a whole cake.
list[start:end:step]
Using Negative Indices: Negative indices count from the end of the list:
numbers = [1, 2, 3, 4, 5]
slice2 = numbers[-3:-1] # from the third last to the second last element print(slice2) # Output: [3, 4]
for x in range(len(someList)): print(x) # this will print out a numerical value up to the length of the original stringList-specific operations and methods
One major difference between lists and tuples is that lists are mutable (changeable) and tuples are immutable (not changeable). There are a few operations and methods that are specific to changing data within lists:
list[index] = x - Replaces the element at index [n] with x.
list.append(x) - Appends x to the end of the list.
list.insert(index, x) - Inserts x at index position [index].
list.pop(index) - Returns the element at [index] and removes it from the list. If [index] position is not in the list, the last element in the list is returned and removed.
list.remove(x) - Removes the first occurrence of x in the list.
list.sort() - Sorts the items in the list.
list.reverse() - Reverses the order of items of the list.
list.clear() - Deletes all items in the list.
list.copy() - Creates a copy of the list.
list.extend(other_list) - Appends all the elements of other_list at the end of list
map(function, iterable) - Applies a given function to each item of an iterable (such as a list) and returns a map object with the results
zip(*iterables) - Takes in iterables as arguments and returns an iterator that generates tuples, where the i-th tuple contains the i-th element from each of the argument iterables.
Tuple use cases
Remember, there are a number of cases where using a tuple might be more suitable than other data types:
Protecting data: Because tuples are immutable, they can be used in situations where you want to ensure the data you have cannot be changed. This can be particularly helpful when dealing with sensitive or important information that should remain constant throughout the execution of a program.
Hashable keys: Because they're immutable, tuples can be used as keys on dictionaries, which can be useful for complex keys.
Efficiency: Tuples are generally more memory-efficient than lists, making them advantageous when dealing with large datasets.
The tuple() operator
The tuple() operator is used to convert an iterable (like a list, string, or set) into a tuple.
# Convert a list to a tuple
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # Outputs: (1, 2, 3, 4)
# Remember that although parentheses are often used to define a tuple,
# they're not always necessary. The following syntax is also valid:
my_tuple = 1, 2, 3, 4
print(my_tuple) # Outputs: (1, 2, 3, 4)
This can sometimes lead to confusion, particularly when tuples are used in function calls or with operators that also use parentheses.
Tuples with mutable objects
Although tuples themselves are immutable, they can contain mutable objects, such as lists. This means that although the tuple cannot be modified (for example, you can't add or remove elements), the mutable elements within the tuple can be changed.
# A tuple with a list as an element
my_tuple = (1, 2, ['a', 'b', 'c'])
# You can't change the tuple itself
# my_tuple[0] = 3 # This would raise a TypeError
# But you can modify the mutable elements within the tuple
my_tuple[2][0] = 'x'
print(my_tuple) # Outputs: (1, 2, ['x', 'b', 'c'])
For Dictionary refer:
https://www.coursera.org/learn/python-crash-course/supplement/Cc19J/study-guide-dictionary-methods