Giter Site home page Giter Site logo

python-3-data-structures-cheat-sheet-tl-dr-edition's Introduction

Python 3 Data Structures Cheat Sheet: TL;DR Edition

Originally written by Daniel Sami (https://github.com/dsesami)

A short reference for data structures in Python 3.x. This page assumes you understand what these data structures are and when to use them (or...not use them). Also assumes you know not to do things like modifying collection ranges when iterating and stuff like that. If you want more detail, check out the official docs.

Complaints? Opinions? Additions? Feel free to make a pull request.

General reference

len(foo) # length of collection
sorted(foo) # returns a sorted version (with dictionaries, sorts keys)
if element in foo: # checks if element is in in foo (with dictionaries, checks the keys)
for i in foo: # iterates over collection (with dictionaries, iterates over keys)

How do I use a...?

List

Ordered, simple, we've all done this before.

foo = []
foo = list()
foo = ['a', 'b', 'c']

foo[0] # returns 'a'
foo[2] = x # changes the list to ['a', 'b', x']
foo.append('d') # add to end of list

foo.pop() # returns 'd' and removes it from the list.
foo.pop() # returns 'x' and removes it from the list.

Dictionary

These now have guaranteed order in Python 3.7.

foo = {}
foo = dict()
foo = {
    'a': 1,
    'b': 2,
    'c': 3
}
foo['b'] # returns 2
foo['d'] = 4
foo.pop('d') # returns 4 and deletes that key-value pair from the dictionary. 

for element in foo: # iterates but only gives you keys. have to access value with foo[element]
for k, v in foo.items() # iterates and gives you keys and values.

Tuple

These are ordered and also immutable, FYI.

foo = ('x',) # need the comma if only one element is present
foo = ('x', 'y', 'z')
foo[1] # returns 'y'

Set

Unordered, good for random insertion and deletion.

foo = set() # only way to do empty sets because it uses brackets like dicts
foo = {'x', 'y', 'z'}

foo.add('a') # use this for one element
foo.update(['a', 'v', 'q']) # use for multiple elements, have to pass an iterable

foo.remove('x') # doesn't return anything
foo.pop('y') # returns 'y' and removes it from the set
foo -= {'z', 'bar'} # removes 'z' and 'bar' from the set (if they exist in there already)

foo.clear() # empties set

Stack / Queue

There's a ton of collections but try to keep it simple when you can. For a stack, you can just use a list (queues aren't very fast in this form):

foo = []
foo.append('alpha')
foo.append('beta')
foo.pop() # returns 'beta'

Or, if you prefer, use the deque (double-ended queue) collection for stacks, as well as queues. Just append/push or pop/remove as you need from either end.

from collections import deque

foo = deque()
foo = deque([], maxlen=10) # won't ever be bigger than 10 items
foo = deque(['a', 'b', 'c'])

foo.append('x') # add to end
foo.pop() # remove from end

foo.appendleft('x') # add to beginning
foo.popleft() # remove from beginning

Note: Built-in functions for data structures also work as conversion functions. set('xyz') and set(['x', 'y', 'z']) would both create a set that looks like {'x', 'y', 'z'}.

python-3-data-structures-cheat-sheet-tl-dr-edition's People

Contributors

dsesami avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.