Low Orbit Flux Logo 2 F

Python - Lists, Tuples, Dictionaries, Sequences

A list is basically an array.

Lists are indexed starting at zero.

Lists can be defined like this:



a = [1, 2, 3]
b = ['a', 'b', 'c']
c = ["pizza", "noodle", "burger"]

Create an empty list:



a = []

Print an entire list like this:



print(a)

Print an element of an list like this:



print(a[2])

Assign an element to a list at a specific index like this:



c[2] = "taco"

Append to a list like this:



c.append("sushi")

Loop over a list. Convert element to string if needed.



for i in c:
    print("element: " + i)

for i in a:
    print("element: " + str(i))

Get the length of an array:



a = [1, 2, 3]
len(a)

List Slicing and Indexing



a = [3, 1, 3, 5, 78, 25, 76, 2, 3, 5]

a[2]               # third element
a[-1]              # last element
x = a + [5, 6, 8]  # combine lists

You can slice a list using a “:” character in the index. You specify the start and end of the slice.

Slicing examples:



a = [3, 1, 3, 5, 78, 25, 76, 2, 3, 5]

a[3:5]  # create slice, values 5, 78
a[-3:]  # -5 to end of list
a[:]    # slice of entire list,  shallow copy

a[4:7] = [9, 8, 7]   # replace values
a[4:7] = []          # remove values
a[:] = []            # clear list

b = a[3:5]       # save slice as new list
print(a[3:5])    # print list

length of list:



a = ['a', 'b', 'c']
len(a)

Nested lists:



a = ['a', 'b', 'c']
b = [1, 2, 3]
c = [a, b]

Access elements in a nested list:



c[0]
c[0][1]

You can create a list using a range like this:



a = list(range(4, 45))
b = list(range(0, 100, 5))

List Functions



a = ["pizza", "noodle", "burger"]

a.append("taco")
a.extend(iterable)

a.insert(5, "taco")
a.insert(0, "taco")         # beginning
a.insert(len(a), "taco")    # append to extend


list.remove("noodle")  # remove first item with matching value

list.pop()     # remove and return last item
list.pop([2])  # remove and return item at index

list.clear()   # remove all items ( same as del a[:] )

list.index("pizza")       # return index of first matching value
list.index("pizza", 5, 12)  # return index of first matching value in slice
list.count("pizza")             # count instances of this value

list.sort(*, key=None, reverse=False) # sort in place

list.reverse()   # reverse list in place
list.copy()    # return shallow copy in place, same as: a[:]

List Sorting

Lists are easy to sort. You can sort in place or return a new sorted copy of a list. See the example below.



a = [4, 3, 6, 5, 7, 1]

b = sorted(a)    # return new sorted list
a.sort()         # sort list in place

Lists as Stacks

Lists can be used as stacks.

Just use append and pop:



a = ["pizza", "burger", "sushi"]
a.append("taco")
a.append("noodel")
a.pop()

Lists as Queues

Don’t use lists as queues. They are inefficient for this purpose. Use collections.deque instead.



from collections import deque
my_q = deque(["pizza", "burger", "sushi"])
my_q.append("taco")
my_q.append("noodle")
my_q.popleft()
my_q.popleft()

List Comprehensions

Lists can be generated using list comprehension. These are basically a nice, compact way of doing things.

Here is an example that takes every number from 0 - 99, multipies it by 5 and assigns it to a list.



z = [x*5 for x in range(100)]

Equivalent:



z = []
for x in range(100):
    z.append(x*5)

This is a more complicated example that generates a list of tuples. It also uses two loops and a conditional expression.



[(x, y) for x in [0,1,2,3,4,5] for y in [4,5,6,7,8,9] if x != y]

Equivalent:



z = []
for x in [0,1,2,3,4,5]:
    for y in [4,5,6,7,8,9]:
        if x != y:
            combs.append((x, y))

Bunch of list comprehension examples:



a = [0, 1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5, 4]

[x*2 for x in a]            # 1 for loop ( basic )
[x+3 for x in [1,2,3]]      # 1 for loop ( basic )
[x for x in a if x > 1]     # for and if
[abs(x) for x in a]         # abs example
[x + y for x in a for y in b]  # 2 for loops

[(x,x*5) for x in a]    # return list of tuples
[[x,x*5] for x in a]    # return list of lists

[(x, y) for x in a for y in b if x != y]  # 2 for loop, if, return tuple

Nested List Comprehensions

This example will transpose a 2d list. Use zip() for this instead.



a = [[1,2,3,4],[5,6,7,8],[12,24,3,1],[15,4,89,800]]

b = [[r[i] for r in a] for i in range(len(a))]

Another example of a nested list comprehension.



a = [1,2,3,4]
b = [[j * i for j in range(len(a))]for i in a]

Deleting Elements with del

You can use del to delete elements or slices.



del a[0]    # delete element at index
del a[2:4]  # delete a slice
del a[:]    # delete all elements ( clear list )

Tuples

Tuples are basically immutable lists.



t = 'burger', 'taco', 'pizza'
t = ('buger', 'taco', 'pizza')
x = t, ('mustard', 'hot sauce')          # nested tuple



t[0]   # index a tuple

Examples of empty or single value tuples:



t = ()       # empty tuple
t = 'pizza',   # tuple with one value
t = ('pizza',) # tuple with one value
t = ('pizza')  # NOT a tuple, needs a comma

Unpack a tuple:



a, b, c = t

Sets

set:



food = {'buger', 'taco', 'buger', 'pizza', 'pizza'}
food = set()  # empty Sets

food = {}     # NOT a set, don't do this, it is a dict

Test membership:



if 'pizza' in food:
    pass

Create a set from a string:



p = set('pizza')
t = set('taco')

Test sets ( these go in conditional statements ):



p - t   # in p but not in t
p | t   # in p or t or both
p & t   # in both p and t
p ^ t   # in p or t but not both

Set comprehensions:



food_letters = {x for x in 'pizza' if x not in 'lmno'}

Dictionaries

Dictionaries or dicts are:

Keys for dicts:

Empty dictionary



d = {}

Creating dictionaries:



d = {'a': 1, 'b': 2, 'c': 3}

d = {'breakfast':'pizza', 'lunch':'burger', 'dinner':'noodles'}

d = dict(breakfast='pizza', lunch='burger', dinner='noodles')
d = dict([('breakfast','pizza'), ('lunch','burger'), ('dinner','noodles')])

You can assign, access, and remove elements in a dictionary like this:



d['lunch'] = 'taco'  # assign a value
d['lunch']           # access a value
del d['lunch']       # remove a value

You can test for membership in a dictionary like this:



if 'pizza' in d:   # check for existence of key
    pass

if 'taco' not in d:
    pass

Stuff you can do with keys:



list(d)    # list of keys in insertion order
sorted(d)   # keys in sorted order

Dict comprehension:



{x: x*5+3 for x in (22, 45, 67, 1)}

Looping Techniques

Dictionary - loop over key and value:



d = {'breakfast':'pizza', 'lunch':'burger', 'dinner':'noodles'}
for k, v in d.items():
    print(k, v)

Dictionary - loop over index and key:



d = {'breakfast':'pizza', 'lunch':'burger', 'dinner':'noodles'}
for i, k in enumerate(d):     # index and key
    print(i, k)

Dictionary - loop over index, key, and value:



d = {'breakfast':'pizza', 'lunch':'burger', 'dinner':'noodles'}
for i, (k, v) in enumerate(d.items()):
    print(i, k, v)

List / sequence - loop over index and value:



for i, v in enumerate(["pizza", "noodle", "burger"]):
    print(i, v)

zip - loop over multiple lists or sequences



meal = ["breakfast", "lunch", "dinner"]
food = ["pizza", "noodle", "burger"]
for a, b in zip(meal, food):
    print(a + ": " + b )

Loop in reverse:



a = ["pizza", "noodle", "burger"]

for i in reversed(a):
    print(i)

for i in reversed(range(1, 50, 3)):
    print(i)

Loop in sorted order:



a = ["pizza", "noodle", "burger"]
for i in sorted(a):
    print(i)

b = [4, 3, 6, 5, 7, 1]
for i in sorted(b):
    print(i)


Loop over sorted, unique elements using set and sorted:



a = ["pizza", "noodle", "burger", "pizza", "apple"]
for i in sorted(set(a)):
    print(i)