Variables

Variable declaration

Type in declaration like:

n: int = 1
n: str = ''

For numbers, you can use _ to make the number more readable in code.

n: int = 100_000

Types & Data Structures

Falsy values

  • False

  • None

  • 0

  • ""

  • (), [] and {}

Can be surronded by either '' or "" .

You may have multiline strings with triple single-quotes or tiple double-quotes:

a: str = """This is a multiline
string.
"""

They can be accessed like arrays str[0].

Check substrings

a = "somestring"

if ("some" in a)
    ...

Lists [] <class 'list'>

Are ordered, changeable and allow duplicates.

  • Ordered means the items have a defined order, and that order will not change.

  • Changeable means that we can change, add, remove items after the list was created.

  • Allow duplicates.

It's items are indexed [0]...[n].

Can have items of different data types.

Access

It can have negative indexing list[-1] that will access from end.

It also index a range list[2:5], not including 5.

Check existence

With in.

Changing and Inserting values

You can change a range of values list[2:5] = ["", "", ""].

Inserting values

Insert values in a fixed position with list.insert(i, value).

Inserting at the end with list.append(value).

Merging lists

You can merge lists with list.extend(list) or by adding list = list + list2.

Removing values

  • Removing by value with list.remove(value).

  • Removing by index with list.pop(i).

  • Removing last item with list.pop().

  • Clear the list with list.clear().

Unpacking values (Destructuring)

Using * will throw the rest of the list to the variable.

[first, second, third] = list
# or
[first, *second] = list

List Comprehensions

s: list[str] = [p for p in people if len(p) > 7]

Sorting lists

Sort them with list.sort(key = myFunc).

Reverse a list list.reverse().

Tuples () <class 'tuple'>

Are ordered, unchangeable and allow duplicates.

  • Unchangeable means that we cannot change, add or remove items after the tuple was created.

It's items are indexed [0]...[n].

Can have items of different data types.

Creating a tuple with one item requires a comma (value,)

Access

Can have negative indexing tuple[-1] that will access from end.

Can also index a range tuple[2:5], not including 5.

Changing, Inserting and Deleting values

Since they are immutable, you must transform them in a list, or create a new tuple.

Unpacking values (Destructuring)

Using * will throw the rest of the list to the variable.

(first, second, third) = list
# or
(first, *second) = list

Merging and Multiplying Tuples

Merge tuples with tup1 + tup2.

Multiply the values of a tuple with tup1 * 5, and this will copy the values 5 times inside the tuple.

Sets {} <class 'set'>

Are unordered, unchangeable, unindexed and cannot have duplicates.

  • Unordered means that items do not have a defined order.

  • Unchangeable means you cannot change its values after it was created, BUT you can INSERT new items and DELETE.

  • Unindexed means that items cannot be referenced by index or key.

Access

Although items cannot be accessed by index, you can loop a set with for x in set.

Check existence

With in.

Adding new values

Add new values with set.add(value).

Merging sets

Merge another set or iterable with set.update(otherSet).

Removing values

  • Remove a value with set.remove(value). (Will raise error if value DONT exists)

  • Remove a value with set.discard(value). (Will NOT raise error if value DONT exists)

  • Remove a random value with set.pop().

Combining sets

set_a: set[int] = {1,2,3,4,5}
set_b: set[int] = {4,5,6,7,8}

comnbined_sets = set_a | set_b

Subtrating sets (Exclusive elements)

set_a: set[int] = {1,2,3,4,5}
set_b: set[int] = {4,5,6,7,8}

comnbined_sets = set_a - set_b

Shared sets (Intersection)

set_a: set[int] = {1,2,3,4,5}
set_b: set[int] = {4,5,6,7,8}

comnbined_sets = set_a & set_b

Unique sets elements

set_a: set[int] = {1,2,3,4,5}
set_b: set[int] = {4,5,6,7,8}

comnbined_sets = set_a ^ set_b

Dictionaries {} <class 'dict'>

Are ordered (in Python >3.6) collections, storing data in key: value pairs.

  • Ordered means that items have a defined order.

  • Changeable means that we can change, add and remove items after its creation.

  • Don't allow Duplicates with the same key.

Access

You can access by key dict[key] or dict.get(key).

Check existence

You can check if a key exists with in.

Keys and values

  • You can get the keys in a list with dict.keys().

  • You can get the values in a list with dict.values().

  • You can get a list of tuples with dict.items() returning [(key, value), ...].

Merge dicts

You can merge dicst with dict.update(otherDict).

Removing items

  • By key with dict.pop(key) or del dict[key].

  • Remove the last item (Only >3.6) with dict.popitem().

Clearing dict

  • You can delete a dict with del dict, but this will also delete the variable.

  • You can clear a dict with dict.clear().

Looping with key, value

Regular for will give you access only to the key.

To loop having the key and value do it with .items().

for key, value in dict.items():
    ...

Copying dicts

You must use newDict = dict.copy().

Or use the dict() constructor.

Arrays

To use them you must import them from NumPy library, and they basically work just like a List.

Generic Types

A better aproach than using Any type.

from typing import Iterable, TypeVar

T = TypeVar('T')

def append_to_list(elements: Iterable[T], target: list[T] = []) -> list[T]:
    target.extend(elements)
    return target

Last updated