codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Python data structures and algorithms

Python data structures and algorithms

Stacks, queues and sorting.

A stack is last-in-first-out (a list with append and pop). A queue is first-in-first-out (collections.deque). Bubble sort swaps neighbours until the list is in order.

Example code

from collections import deque

stack = []
stack.append(1)
stack.append(2)
print(stack.pop())

q = deque([1, 2, 3])
q.popleft()
print(list(q))

def bubble(a):
    a = a[:]
    for i in range(len(a)):
        for j in range(len(a) - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
    return a

print(bubble([5, 2, 9, 1]))

Run this code in the online editor

← Python statistics and machine learning basicsPython databases: MySQL and MongoDB →