Concatenate two lists
li + other_li
Remove 3’rd element of a list
del li[2]
Remove 3rd and 4th element from a list
del a[2:4]
Make a copy of a list
list.copy()a[:]
What will list2 = list do?
id(list) == id(list2) # => True
Both points to the same object
Check for element 1 in list li
1 in li
List:
- Add Single element
- Add multiple elements (from an iterable)
- Insert element x at index 1
list.append(x) list.extend(iterable) list.insert(1, x) # Insert x at index 1
List:
- Remove first occurrence of x
- Remove the item at the given position / last in the list, and return it
- Remove all elements from a list
list.remove(x) # Remove first occurrence of x list.pop([i]) # Remove the item at the given position / last in the list, and return it list.clear()
List: Search for element x, starting at 0, ending at index 5 inclusive
list.index(x, 0, 6)
Find number of times x appears in the list.
list.count(x)
List comprehension with filtering example
[x for x in [3, 4, 5, 6, 7] if x > 5]
How to sort and reverse a list?
list.sort(key=None, reverse=False) list.reverse()
What are tuples?
Like lists but immutable
tup = (1, 2, 3)
How to define tuple with single element?
type((1)) # => <class 'int'> !!! type((1,)) # => <class 'tuple'> (add ,)
How to define a dictionary?
- Empty
- With some values
- From a list
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
dict_from_kv_pairs = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])How to get an element from a dictionary? Both methods, how they differ
filled_dict["one"]
Throws Key Error when element not found
filled_dict.get("four")
Returns None when element not found
filled_dict.get("four", default)
Returns default when element not found
Get list of keys and values from a dictionary
list(filled_dict.keys()) # => ["one", "two", "three"] list(filled_dict.values()) # => [1, 2, 3]
Check if one is a key in a dictionary
“one” in filled_dict
How to update dictionary value under key “one”
filled_dict["one"] = 5
How to delete dictionary value under key "one"
del filled_dict["one"]
Dictionary comprehension where each value is a square of its key (for keys 2, 4, 6)
{x: x**2 for x in (2, 4, 6)}
Define some set with initial values
some_set = {1, 1, 2, 2, 3, 4}
Define an empty set
empty_set = set()
Check if value is inside of a set
1 in some_set