Python Collections

list1 + list2

Note: l1 + l2 won’t change the value of l1

list.append(x)

Append a new item with value x to the end of the array

list.extend(iterable)

Append items from iterable to the end of the array

list.insert(i, x)

Insert a new item with value x in the array before position i

del

  1. del works against a mutable iterable when deleting object at a index

  2. del won’t work against an immutable iterable, such as a str

  3. Use del as dealloc

list.remove(x)

Remove the first occurrence of x or raise an exception when x is not in the list.

list.pop(i)

Remove and return the item at index (default last).

Basic Slice

Slice works against both list and str

[:] will get back the entire list; more important thing is the returned list is a COPY of the original one.

Comparing to [:], sort() also returns a list, but it is still the original one.

Slice with Step

Basic pattern: some_list[start:end:step]. start is included, but end doesn’t.

Since str is a list of characters, so this pattern also works against str.

Negative index

Delete and Replace Slice

Super straightforward and intuitive

Dictionary

Basics

Key: value pairs. Dictionary can be in another dictionary.

Key can be of type other than str.

Managing Keys

Use del keyword to delete a key.

Update the value of a key (key will be created if it doesn’t exist).

Update value of multiple keys at once.

Unpacking Dictionaries

Example: str.format()

param order doesn’t matter

pass in a dictionary and pull out needed info

Dictionary Iteration

Simple for in statement (treat my_dict like a list) will get back the keys.

Dictionaries have a method called values() which returns the values.

Tuples

Basics

Create a tuple: comma makes a tuple a really tuple

Tuples are immutable. They can be accessed by index.

Tuple Packing and Unpacking

Swap value of two variables using tuple

Return a tuple from a function

Tuple with Functions

Use enumerate() to loop through an iterable

** unpacks a dictionary, and * unpacks a tuple

Loop through a dictionary using tuple

Useful Function(s)

random.choice(seq)

Choose a random element from a non-empty sequence.

Leave a Reply

Your email address will not be published. Required fields are marked *