mkaz.blog

Working with Python

Lists

The primary data structure for collections in Python are lists. Lists are a built-in data structure and are ordered, mutable, and a single list can contain items of different types.

Create Lists

Python lists are defined using square brackets [ ]

a = ["a", "b", "c"]

Append item to list

a = [1, 2, 3]
a.append(4)
a
>>> [1, 2, 3, 4]

How to concatenate two lists

To concatenate two lists together in Python use the + operator.

a = [1, 2, 3]
b = [4, 5, 6]
a + b
>>> [1, 2, 3, 4, 5, 6]

Count elements in a list

Use the len() function to get a count of all elements in alist.

a = ["a", "b", "c"]
len(a)
>>> 3

Count specific elements in a list

Use .count() method to count how many occurrences of a specific item exists in a list:

a = ["a", "b", "b", "c"]
a.count("b")
>> 2

Initialize a two dimensional array

To create a two dimensional array and initialize with all 0

width, height = 100, 50
matrix = [[o for x in range(width)] for y in range[height]]

How to iterate over a list

To iterate over a list in Python:

a = ["a", "b", "c"]
for item in a:
    print(item)
>>> a
>>> b
>>> c

Iterate over a list with index

Use the enumerate() function to iterate with an index:

a = ["a", "b", "c"]
for idx, item in enumerate(a):
    print(f"{idx} -> {item}")
0 -> a
1 -> b
2 -> c
>>>

Sorting Lists

Python has several built-in functions to sort lists.

Sort list by value

Use the .sort() method to alter the list sorting by value:

a = [3, 2, 1]
a.sort()
a
>>> [1, 2, 3]
 
 
b = ["c", "b", "a"]
b.sort()
b
>>> ['a', 'b', 'c']

Reverse list order

Use the .reverse() method to alter the list reversing the order:

a = ["a", "b", "c"]
a.reverse()
a
>>> ['c', 'b', 'a']

Iterate over list in reverse order

To iterate over a list in reverse order, not changing the list, use the reversed() iterator function:

a = ["a", "b", "c"]
for item in reversed(a):
    print(item)
>>> c
>>> b
>>> a

Remove item from list

You can use the .pop() method to remove an item at a specific index, if no index specified it will remove the last item. .pop() returns the item removed.

a =["a", "b", "c"]
item = a.pop(1)
print(f"List: {a}, Item: {item}")
>>> List: ['a', 'c'], Item: b

Remove item by value from list

You can remove an item by value from list using .remove() but this is not as convenient to use, it will only remove the first item found and will raise a ValueError if not found.

a = ["a", "b", "b", "c"]
a.remove("b")
a
>>> ['a', 'b', 'c']
 
a.remove("z")
>>> ValueError: list.remove(x): x not in list

Use the filter() function as a better means to remove all items matching a value. The filter function returns a filter object that needs to be converted back to a list:

a = ["a", "b", "b", "c"]
list(filter(lambda e: e != "b", a)
>>> ['a', 'c']

Resources