python - ghdrako/doc_snipets GitHub Wiki

b,a = a,b

divmod(20,8)
t=[20,8]
divmod(*t) # rozpakowanie sekwencji *
quotient,remainder = divmod(*t)
a,b,*rest = range(5)
a,*body,c,d = range(5)
*head,b,c,d = range(5)
[record]=query_returning_single_row()
[field](/ghdrako/doc_snipets/wiki/field)=query_returning_single_row_with_single_value()
(record,),=query_returning_single_row()
((field,),)=query_returning_single_row_with_single_value()

Convert string to number

>>> float("3.25")
3.25
>>> float("-2")
-2.0
>>> int("-5")
-5
>>> int("123")
123
def cast_number(number_str):
  try:
    casted_number = float(number_str)
  except ValueError:
    print(f"Couldn't cast {repr(number_str)} to a number")
  else:
    print(f"Casting {repr(number_str)} to {casted_number}")

>>> cast_number("1.5")
Casting '1.5' to 1.5
>>> cast_number("2.3a")
Couldn't cast '2.3a' to a number
assert "Homework".isalpha() == True
assert "Homework123".isalpha() == False
assert "123".isnumeric() == True
assert "a123".isnumeric() == False
assert "3.5".isnumeric() == False # Strings that represent floats won’t pass the isnumeric check
assert "-2".isnumeric() == False # Strings that represent negative integers won’t pass the isnumeric check
# Empty strings are evaluated as False with isnumeric 

String join

tasks = ["Homework", "Grocery", "Laundry", "Museum Trip", "Buy Furniture"]
note = ", ".join(tasks)
print("Remaining Tasks:", note)
# output: Remaining Tasks: Homework, Grocery, Laundry, Museum Trip, Buy Furniture

Splitting strings to create a list of strings

task_data = """1001,Homework,5
1002,Laundry,3
1003,Grocery,4"""  # triple-quoted string that expands multiple lines


processed_tasks = []
for data_line in task_data.split("\n"):
  processed_task = data_line.split(",")
  processed_tasks.append(processed_task)
print(processed_tasks)
# output the following line:
['1001', 'Homework', '5'], ['1002', 'Laundry', '3'], ['1003', 'Grocery', '4'](/ghdrako/doc_snipets/wiki/'1001',-'Homework',-'5'],-['1002',-'Laundry',-'3'],-['1003',-'Grocery',-'4')

Lists

Description Operation Item in the list
Creating a list numbers = [1, 2, 3] [1, 2, 3]
Inserting an item at specified index numbers.insert (0, 0) [0, 1, 2, 3]
Appending an item to the end numbers.append (4) [0, 1, 2, 3, 4]
Extending the list with multiple items numbers.extend ([5, 6, 7]) [0, 1, 2, 3, 4, 5, 6, 7]
Removing an item by specifying the value numbers.remove (5) [0, 1, 2, 3, 4, 6, 7]
Removing an item at specified index del numbers [3] [0, 1, 2, 4, 6, 7]

Lists’ remove method deletes only the first matching item. When you’re removing an item that isn’t in the list , you encounter a ValueError

Check whether a list contains the entirety of another list

def all_contained_in_recommended(recommended, personal):
  print(f"Is {personal} contained in {recommended}?")
  for stock in personal:
    if stock not in recommended:
      return False
  return True

Better solution using set:

good_stocks_set = set(good_stocks)
contained0 = good_stocks_set.issuperset(client0)

To use the issuperset method, we convert the list object good_stocks to a set object good_stocks_set . We call issuperset on the good_stocks_set and pass the list object client0

Theoretically, we can use the issubset method to implement this functional- ity, but it requires creating set objects for each client’s list, which is unnecessary repe- tition. For this reason, issuperset is better than issubset when you share a set object that presumably is the superset.

Sorting List

Note that the sorting operation is conducted in place, meaning that sorting changes the order of the original list instead of creating a new list . Related to this in-place feature, sort returns None .

The default sorting order is ascending. If you specify the reverse parameter as True , you’ll get the list in descending order.

numbers = [12, 4, 1, 3, 7, 5, 9, 8]
numbers.sort()
print(numbers)
# output: [1, 3, 4, 5, 7, 8, 9, 12]
names = ['Danny', 'Aaron', 'Zack', 'Jennifer', 'Mike', 'David']
names.sort(reverse=True)
print(names)
# output: ['Zack', 'Mike', 'Jennifer', 'David', 'Danny', 'Aaron']

a strategy for sorting data of different types is to convert it to strings by setting the key parameter

mixed = [3, 1, 2, 'John', ['c', 'd'], ['a', 'b']]
mixed.sort(key=str)
print(mixed)
# output: [1, 2, 3, 'John', ['a', 'b'], ['c', 'd']]

Using custom functions for more complicated sorting needs

def using_urgency_level(task):
return task['urgency']
tasks.sort(key=using_urgency_level, reverse=True)
print(tasks)
# output the following lines (re-arranged for readability):
[{'title': 'Homework', 'desc': 'Physics + Math', 'urgency': 5},
{'title': 'Laundry', 'desc': 'Wash clothes', 'urgency': 3},
{'title': 'Museum', 'desc': 'Egyptian things', 'urgency': 2}]

using lambda function

tasks.sort(key=lambda x: x[ ' urgency ' ],reverse=True)

A key function converts each item of the list to a corresponding value. The generated values will be used as intermediate items to sort the list. After the sorting, the original items are rendered in the order created by the intermediate items.

The sort method works only with lists because it’s an instance method of lists. When we sort other container data types, such as tuples, sets, and dictionaries, we can use sorted , which can take any iterable and return a sorted list . You can specify a custom sorting function for sorted , too. Remember that the function to be set to the key argument should take exactly one parameter.

Tuples

named tuples

from collections import namedtuple
Task = namedtuple('Task', 'title desc urgency')  # declare named tuple class with 3 fields title desc and urgency
task_nt = Task('Laundry', 'Wash clothes', 3)
assert task_nt.title == 'Laundry'
assert task_nt.desc == 'Wash clothes'

the data model’s attributes can be set as either a single string (with spaces or commas as separators) or a list object

Task = namedtuple('Task', ['title', 'desc', 'urgency'])

Convert the text data to Task instance objects

task_data = '''Laundry,Wash clothes,3
Homework,Physics + Math,5
Museum,Epyptian things,2'''

for task_text in task_data.split('\n'):
  title, desc, urgency = task_text.split(',')
  task_nt = Task(title, desc, int(urgency))
  print(f"--> {task_nt}")
# output the following lines
--> Task(title='Laundry', desc='Wash clothes', urgency=3)
--> Task(title='Homework', desc='Physics + Math', urgency=5)
--> Task(title='Museum', desc='Epyptian things', urgency=2)

Use named tuple class method _make , which maps an iterable (the list created by split is an iterable to the named tuple.

for task_text in task_data.split('\n'):
  task_nt = Task._make(task_text.split(','))

Unlike custom classes, whose instances have per-instance dict representations through dict , named tuples don’t have the underlying dict representations, which makes named tuples a lightweight data model with negligible memory costs. Named tuples can save significant amounts of memory when you need to create thousands of instances.

Dictionary

urgencies = {"Laundry": 3, "Homework": 5, "Museum": 2}

Using dynamic view objects (keys, values, and items) directly

urgencies = {"Laundry": 3, "Homework": 5, "Museum": 2}
urgen_keys = urgencies.keys()
urgen_values = urgencies.values()
urgen_items = urgencies.items()
print(urgen_keys, urgen_values, urgen_items, sep="\n")
# output the following lines:
dict_keys(['Laundry', 'Homework', 'Museum'])
dict_values([3, 5, 2])
dict_items([('Laundry', 3), ('Homework', 5), ('Museum', 2)])

Like views in a database, dictionary view objects are dynamic, updated automatically with the change of the dict object. That is, whenever you modify the key-value pairs stored in a dict object, these view objects get updated. Observe this effect:

urgencies["Grocery Shopping"] = 4
print(urgen_keys)
# output: dict_keys(['Laundry', 'Homework', 'Museum', 'Grocery])
print(urgen_values)
# output: dict_values([3, 5, 2, 4])
print(urgen_items)
# output: dict_items([('Laundry', 3), ('Homework', 5), ('Museum', 2),
➥ ('Grocery, 4)])

This dynamic provides great convenience when we access a dictionary’s data because the data is in perfect sync with the dict object. By contrast anypattern:

urgencies = {"Laundry": 3, "Homework": 5, "Museum": 2}
urgen_keys_list = list(urgencies.keys())
print(urgen_keys_list)
# output: ['Laundry', 'Homework', 'Museum']
urgencies["Grocery"] = 4
print(urgen_keys_list)
# output: ['Laundry', 'Homework', 'Museum']

We create a list for the keys. After we update the dictionary, the list stays the same and doesn’t sync with the dict object.

access a single value

assert urgencies["Laundry"] == 3
assert urgencies["Homework"] == 5
urgencies["Homeworks"]
# ERROR: KeyError: 'Homeworks'

if "Homework" in urgencies:
urgency = urgencies["Homework"]
else:
urgency = "N/A"

def retrieve_urgency(task_title):
  if task_title in urgencies:
    urgency = urgencies[task_title]
  else:
    urgency = "N/A"
  return urgency

urgencies.get("Homework")
# output: 5
urgencies.get("Homeworks", "N/A")
# output: 'N/A'
urgencies.get("Homeworks")
# output: None (None is automatically hidden in an interactive console)
urgencies = {"Laundry": 3, "Homework": 5, "Museum": 2}
urgencies.setdefault("Homework")
# output: 5
urgencies.setdefault("Homeworks", 0)
# output: 0
urgencies.setdefault("Grocery")
# output: None (None is automatically hidden in an interactive console)
print(urgencies)
# output: {'Laundry': 3, 'Homework': 5, 'Museum': 2, 'Homeworks': 0,
➥ 'Grocery': None}
We previously called setdefault with the keys "Homework" , "Homeworks" , and
"Grocery". Because the latter two keys were not in the dict initially, the following
operations occurred under the hood:
urgencies["Homeworks"] = 0
urgencies["Grocery"] = None

Set

Using the intersection operator & , we conveniently retrieve the intersection between two set objects.

good_stocks_set & set(client0)
# output: {'AMZN', 'GOOG'}
bool(good_stocks_set & set(client0))
# output: True
good_stocks_set & set(client1)
# output: {'AMZN'}
bool(good_stocks_set & set(client1))
# output: True

what makes intersection convenient is that it can take any iterable in such a way that we can send the list objects client0 and client1 directly to the method without converting them to set objects first

good_stocks_set.intersection(client0)
# output: {'AMZN', 'GOOG'}
good_stocks_set.intersection(client1)
# output: {'AMZN'}
tasks_a = {"Homework", "Laundry", "Grocery"}
tasks_b = {"Laundry", "Gaming"}
tasks_a | tasks_b   # Union operation with |
# output: {'Laundry', 'Gaming', 'Homework', 'Grocery'}
tasks_a & tasks_b # Intersection operation with &
# output: {'Laundry'}
tasks_a ^ tasks_b # Symmetric difference operation with ^
# output: {'Homework', 'Grocery', 'Gaming'}
tasks_a - tasks_b # Difference operation with -
# output: {'Homework', 'Grocery'}

Set operators and their corresponding methods

Set operation Operator Method
Union | union
Intersection & intersection
Symmetric difference ^ symmetric_difference
Difference - difference
Checks whether one set is a superset of the other >= issuperset
Checks whether one set is a subset of the other <= issubset
Checks whether one set is a strict superset of the other > N/A but can be achieved by combining issuperset and !=
Checks whether one set is a strict subset of the other < N/A but can be achieved by combining issubset and !=

Although operators make your code more concise, they work only with set objects. By contrast, all these methods can take iterables as their parameters; thus, they’re more flexible. When you deal with iterables that aren’t set objects, you should consider using these methods directly, which eliminates the need to convert them to set objects first.