{"id":18611050,"url":"https://github.com/beangreen247/data-structures-in-python","last_synced_at":"2026-04-10T01:04:44.191Z","repository":{"id":153757077,"uuid":"239304541","full_name":"BeanGreen247/Data-Structures-In-Python","owner":"BeanGreen247","description":"Studying material about Data Structures In Python","archived":false,"fork":false,"pushed_at":"2020-02-09T13:01:32.000Z","size":63,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-15T08:32:12.898Z","etag":null,"topics":["arch","beangreen","beangreen247","data-structures","debian","linux","markdow","material","open","python","source","study","unix"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BeanGreen247.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-02-09T12:54:47.000Z","updated_at":"2020-02-09T13:24:27.000Z","dependencies_parsed_at":null,"dependency_job_id":"8b4671d0-e42e-4a9b-b54d-0b25c282ad16","html_url":"https://github.com/BeanGreen247/Data-Structures-In-Python","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BeanGreen247%2FData-Structures-In-Python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BeanGreen247%2FData-Structures-In-Python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BeanGreen247%2FData-Structures-In-Python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BeanGreen247%2FData-Structures-In-Python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BeanGreen247","download_url":"https://codeload.github.com/BeanGreen247/Data-Structures-In-Python/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239400687,"owners_count":19632068,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arch","beangreen","beangreen247","data-structures","debian","linux","markdow","material","open","python","source","study","unix"],"created_at":"2024-11-07T03:12:29.762Z","updated_at":"2025-11-02T21:30:32.171Z","avatar_url":"https://github.com/BeanGreen247.png","language":null,"readme":"# Data structures in Python\n\nThere are quite a few data structures available. The builtins data structures are: lists, tuples, dictionaries, strings, sets and frozensets.\n\nLists, strings and tuples are ordered sequences of objects. Unlike strings that contain only characters, list and tuples can contain any type of objects. Lists and tuples are like arrays. Tuples like strings are immutables. Lists are mutables so they can be extended or reduced at will. Sets are mutable unordered sequence of unique elements whereas frozensets are immutable sets.\n\nLists are enclosed in brackets:\n```\nl = [1, 2, \"a\"]\n```\nTuples are enclosed in parentheses:\n```\nt = (1, 2, \"a\")\n```\nTuples are faster and consume less memory. See Tuples for more information.\n\nDictionaries are built with curly brackets:\n```\nd = {\"a\":1, \"b\":2}\n```\nSets are made using the set() builtin function. More about the data structures here below:\n\n* [Lists](#Lists)\n* [Tuples](#Tuples)\n* [Dicts](#Dicts)\n* [Strings](#Strings)\n* [Sets](#Sets)\n* [Frozensets](#Frozensets)\n\nThere are additional data structures available in the [collections](#the-collections-module) and [heapq](#the-heapq-module) modules for instance.\n\n## Lists\n\nIn python, lists are part of the standard language. You will find them everywhere. Like almost everything in Python, lists are objects. There are many methods associated to them. Some of which are presented here below.\n\nQuick example\n```\n\u003e\u003e\u003e l = [1, 2, 3]\n\u003e\u003e\u003e l[0]\n1\n\u003e\u003e\u003e l.append(1)\n\u003e\u003e\u003e l\n[1, 2, 3, 1]\n```\n\nDifference between append() and extend()\n\nLists have several methods amongst which the append() and extend() methods. The former appends an object to the end of the list (e.g., another list) while the later appends each element of the iterable object (e.g., anothee list) to the end of the list.\n\nFor example, we can append an object (here the character ‘c’) to the end of a simple list as follows:\n```\n\u003e\u003e\u003e stack = ['a','b']\n\u003e\u003e\u003e stack.append('c')\n\u003e\u003e\u003e stack\n['a', 'b', 'c']\n```\nHowever, if we want to append several objects contained in a list, the result as expected (or not...) is:\n```\n\u003e\u003e\u003e stack.append(['d', 'e', 'f'])\n\u003e\u003e\u003e stack\n['a', 'b', 'c', ['d', 'e', 'f']]\n```\nThe object ['d', 'e', 'f'] has been appended to the exiistng list. However, it happens that sometimes what we want is to append the elements one by one of a given list rather the list itself. You can do that manually of course, but a better solution is to use the extend() method as follows:\n```\n\u003e\u003e\u003e stack = ['a', 'b', 'c']\n\u003e\u003e\u003e stack.extend(['d', 'e','f'])\n\u003e\u003e\u003e stack\n['a', 'b', 'c', 'd', 'e', 'f']\n```\n### Other list methods\n\n#### index\n\nThe index() methods searches for an element in a list. For instance:\n```\n\u003e\u003e\u003e my_list = ['a','b','c','b', 'a']\n\u003e\u003e\u003e my_list.index('b')\n1\n```\nIt returns the index of the first and only occurence of ‘b’. If you want to specify a range of valid index, you can indicate the start and stop indices:\n```\n\u003e\u003e\u003e my_list = ['a','b','c','b', 'a']\n\u003e\u003e\u003e my_list.index('b', 2)\n3\n```\n\u003eWarning\n\u003e\n\u003eif the element is not found, an error is raised\n\n#### insert\n\nYou can remove element but also insert element wherever you want in a list:\n```\n\u003e\u003e\u003e my_list.insert(2, 'a')\n\u003e\u003e\u003e my_list\n['b', 'c', 'a', 'b']\n```\nThe insert() methods insert an object before the index provided.\n\n#### remove\n\nSimilarly, you can remove the first occurence of an element as follows:\n```\n\u003e\u003e\u003e my_list.remove('a')\n\u003e\u003e\u003e my_list\n['b', 'c', 'b', 'a']\n```\n\n#### pop\n\nOr remove the last element of a list by using:\n```\n\u003e\u003e\u003e my_list.pop()\n'a'\n\u003e\u003e\u003e my_list\n['b', 'c', 'b']\n```\nwhich also returns the value that has been removed.\n\n#### count\n\nYou can count the number of element of a kind:\n```\n\u003e\u003e\u003e my_list.count('b')\n2\n```\n\n#### sort\n\nThere is a sort() method that performs an in-place sorting:\n```\n\u003e\u003e\u003e my_list.sort()\n\u003e\u003e\u003e my_list\n['a', 'b', 'b', 'c']\n```\n\nHere, it is quite simple since the elements are all characters. For standard types, the sorting works well. Imagine now that you have some non-standard types. You can overwrite the function used to perform the comparison as the first argument of the sort() method.\n\nThere is also the possiblity to sort in the reverse order:\n```\n\u003e\u003e\u003e my_list.sort(reverse=True)\n\u003e\u003e\u003e my_list\n['c', 'b', 'b', 'a']\n```\n\n#### reverse\n\nFinally, you can reverse the element in-place:\n```\n\u003e\u003e\u003e my_list = ['a', 'c' ,'b']\n\u003e\u003e\u003e my_list.reverse()\n\u003e\u003e\u003e my_list\n['b', 'c', 'a']\n```\n###  Operators\n\nThe + operator can be used to extend a list:\n```\n\u003e\u003e\u003e my_list = [1]\n\u003e\u003e\u003e my_list += [2]\n\u003e\u003e\u003e my_list\n[1, 2]\n\u003e\u003e\u003e my_list += [3, 4]\n\u003e\u003e\u003e my_list\n[1, 2, 3, 4]\n```\nThe * operator ease the creation of list with similar values\n```\n\u003e\u003e\u003e my_list = [1, 2]\n\u003e\u003e\u003e my_list = my_list * 2\n\u003e\u003e\u003e my_list\n[1, 2, 1, 2]\n```\n### Slicing\n\nSlicing uses the symbol : to access to part of a list:\n```\n\u003e\u003e\u003e list[first index:last index:step]\n\u003e\u003e\u003e list[:]\n\n\u003e\u003e\u003e a = [0, 1, 2, 3, 4, 5]\n[0, 1, 2, 3, 4, 5]\n\u003e\u003e\u003e a[2:]\n[2, 3, 4, 5]\n\u003e\u003e\u003e a[:2]\n[0, 1]\n\u003e\u003e\u003e a[2:-1]\n[2, 3, 4]\n```\nBy default the first index is 0, the last index is the last one..., and the step is 1. The step is optional. So the following slicing are equivalent:\n```\n\u003e\u003e\u003e a = [1, 2, 3, 4, 5, 6, 7, 8]\n\u003e\u003e\u003e a[:]\n[1, 2, 3, 4, 5, 6, 7, 8]\n\u003e\u003e\u003e a[::1]\n[1, 2, 3, 4, 5, 6, 7, 8]\n\u003e\u003e\u003e a[0::1]\n[1, 2, 3, 4, 5, 6, 7, 8]\n```\n### List comprehension\n\nTraditionally, a piece of code that loops over a sequence could be written as follows:\n```\n\u003e\u003e\u003e evens = []\n\u003e\u003e\u003e for i in range(10):\n...     if i % 2 == 0:\n...         evens.append(i)\n\u003e\u003e\u003e evens\n[0, 2, 4, 6, 8]\n```\nThis may work, but it actually makes things slower for Python because the interpreter works on each loop to determine what part of the sequence has to be changed.\n\nA list comprehension is the correct answer:\n```\n\u003e\u003e\u003e [i for i in range(10) if i % 2 == 0]\n[0, 2, 4, 6, 8]\n```\nBesides the fact that it is more efficient, it is also shorter and involves fewer elements.\n\n### Filtering Lists\n```\n\u003e\u003e\u003e li = [1, 2]\n\u003e\u003e\u003e [elem*2 for elem in li if elem\u003e1]\n[4]\n```\n### Lists as Stacks\n\nThe Python documentation gives an example of how to use lists as stacks, that is a last-in, first-out data structures (LIFO).\n\nAn item can be added to a list by using the append() method. The last item can be removed from the list by using the pop() method without passing any index to it.\n```\n\u003e\u003e\u003e stack = ['a','b','c','d']\n\u003e\u003e\u003e stack.append('e')\n\u003e\u003e\u003e stack.append('f')\n\u003e\u003e\u003e stack\n['a', 'b', 'c', 'd', 'e', 'f']\n\u003e\u003e\u003e stack.pop()\n'f'\n\u003e\u003e\u003e stack\n['a, 'b', 'c', 'd', 'e']\n```\n### Lists as Queues\n\nAnother usage of list, again presented in Python documentation is to use lists as queues, that is a first in - first out (FIFO).\n```\n\u003e\u003e\u003e queue = ['a', 'b', 'c', 'd']\n\u003e\u003e\u003e queue.append('e')\n\u003e\u003e\u003e queue.append('f')\n\u003e\u003e\u003e queue\n['a', 'b', 'c', 'd', 'e', 'f']\n\u003e\u003e\u003e queue.pop(0)\n'a'\n```\n### How to copy a list\n\nThere are three ways to copy a list:\n```\n\u003e\u003e\u003e l2 = list(l)\n\u003e\u003e\u003e l2 = l[:]\n\u003e\u003e\u003e import copy\n\u003e\u003e\u003e l2 = copy.copy(l)\n```\n\u003eWarning\n\u003e\n\u003eDon’t do l2 = l, which is a reference, not a copy.\n\nThe preceding techniques for copying a list create shallow copies. IT means that nested objects will not be copied. Consider this example:\n```\n\u003e\u003e\u003e a = [1, 2, [3, 4]]\n\u003e\u003e\u003e b = a[:]\n\u003e\u003e\u003e a[2][0] = 10\n\u003e\u003e\u003e a\n[1, 2, [10, 4]]\n\u003e\u003e\u003e b\n[1, 2, [10, 4]]\n```\nTo get around this problem, you must perform a deep copy:\n```\n\u003e\u003e\u003e import copy\n\u003e\u003e\u003e a = [1, 2, [3, 4]]\n\u003e\u003e\u003e b = copy.deepcopy(a)\n\u003e\u003e\u003e a[2][0] = 10\n\u003e\u003e\u003e a\n[1, 2, [10, 4]]\n\u003e\u003e\u003e b\n[1, 2, [3, 4]]\n```\n#### Inserting items into a sorted list\n\nThe bisect module provides tools to manipulate sorted lists.\n```\n\u003e\u003e\u003e x = [4, 1]\n\u003e\u003e\u003e x.sort()\n\u003e\u003e\u003e import bisect\n\u003e\u003e\u003e bisect.insort(x, 2)\n\u003e\u003e\u003e x\n[1, 2, 4]\n```\nTo know where the index where the value would have been inserted, you could have use:\n```\n\u003e\u003e\u003e x = [4, 1]\n\u003e\u003e\u003e x.sort()\n\u003e\u003e\u003e import bisect\n\u003e\u003e\u003e bisect.bisect(x, 2)\n```\n## Tuples\n\nIn Python, tuples are part of the standard language. This is a data structure very similar to the list data structure. The main difference being that tuple manipulation are faster than list because tuples are immutable.\n\n### Constructing tuples\n\nTo create a tuple, place values within brackets:\n```\n\u003e\u003e\u003e l = (1, 2, 3)\n\u003e\u003e\u003e l[0]\n1\n```\nIt is also possible to create a tuple without parentheses, by using commas:\n```\n\u003e\u003e\u003e l = 1, 2\n\u003e\u003e\u003e l\n(1, 2)\n```\nIf you want to create a tuple with a single element, you must use the comma:\n```\n\u003e\u003e\u003e singleton = (1, )\n```\nYou can repeat a tuples by multiplying a tuple by a number:\n```\n\u003e\u003e\u003e (1,) * 5\n\u003e\u003e\u003e (1, 1, 1, 1, 1)\n```\nNote that you can concatenate tuples and use augmented assignement (*=, +=):\n```\n\u003e\u003e\u003e s1 = (1,0)\n\u003e\u003e\u003e s1 += (1,)\n\u003e\u003e\u003e s1\n\u003e\u003e\u003e (1, 0, 1)\n```\n### Tuple methods\n\nTuples are optimised, which makes them very simple objects. There are two methods available only:\n\n* index, to find occurence of a value\n* count, to count the number of occurence of a value\n```\n\u003e\u003e\u003e l = (1,2,3,1)\n\u003e\u003e\u003e l.count(1)\n\u003e\u003e\u003e 2\n\u003e\u003e\u003e l.index(2)\n\u003e\u003e\u003e 1\n```\n### Interests of tuples\n\nSo, Tuples are useful because there are\n\n* faster than lists\n* protect the data, which is immutable\n* tuples can be used as keys on dictionaries\n\nIn addition, it can be used in different useful ways:\n\n#### Tuples as key/value pairs to build dictionaries\n```\n\u003e\u003e\u003e d = dict([('jan', 1), ('feb', 2), ('march', 3)])\n\u003e\u003e\u003e d['feb']\n\u003e\u003e\u003e 2\n```\n#### signing multiple values\n```\n\u003e\u003e\u003e (x,y,z) = ('a','b','c')\n\u003e\u003e\u003e x\n\u003e\u003e\u003e 'a'\n\u003e\u003e\u003e (x,y,z) = range(3)\n\u003e\u003e\u003e x\n\u003e\u003e\u003e 0\n```\n#### Tuple Unpacking\n\nTuple unpacking allows to extract tuple elements automatically is the list of variables on the left has the same number of elements as the length of the tuple\n```\n\u003e\u003e\u003e data  = (1,2,3)\n\u003e\u003e\u003e x, y, z = data\n\u003e\u003e\u003e x\n\u003e\u003e\u003e 1\n```\n#### Tuple can be use as swap function\n\nThis code reverses the contents of 2 variables x and y:\n```\n\u003e\u003e\u003e (x,y) = (y,x)\n```\n\u003eWarning\n\u003e\n\u003eConsider the following function:\n```\ndef swap(a, b):\n    (b, a) = (a, b)\n```\nthen:\n```\na = 2\nb = 3\nswap(a, b)\n#a is still 2 and b still 3 !! a and b are indeed passed by value not reference.\n```\n### Misc\n\n#### length\n\nTo find the length of a tuple, you can use the len() function:\n```\n\u003e\u003e\u003e t= (1,2)\n\u003e\u003e\u003e len(t)\n\u003e\u003e\u003e 2\n```\n#### Slicing (extracting a segment)\n```\n\u003e\u003e\u003e t = (1,2,3,4,5)\n\u003e\u003e\u003e t[2:]\n\u003e\u003e\u003e (3, 4, 5)\n```\n#### Copy a tuple\n\nTo copy a tuple, just use the assignement:\n```\n\u003e\u003e\u003e t = (1, 2, 3, 4, 5)\n\u003e\u003e\u003e newt = t\n\u003e\u003e\u003e t[0] = 5\n\u003e\u003e\u003e newt\n\u003e\u003e\u003e (1, 2, 3, 4, 5)\n```\n\u003eWarning\n\u003e\n\u003eYou cannot copy a list with the = sign because lists are mutables. The = sign creates a reference not a copy. Tuples are immutable therefore a = sign does not create a reference but a copy as expected.\n\n#### Tuple are not fully immutable !!\n\nIf a value within a tuple is mutable, then you can change it:\n```\n\u003e\u003e\u003e t = (1, 2, [3, 10])\n\u003e\u003e\u003e t[2][0] = 9\n\u003e\u003e\u003e t\n\u003e\u003e\u003e (1, 2, [9, 10])\n```\n#### Convert a tuple to a string\n\nYou can convert a tuple to a string with either:\n```\n\u003e\u003e\u003e str(t)\n```\nor\n```\n\u003e\u003e\u003e `t`\n```\n#### math and comparison\n\ncomparison operators and mathematical functions can be used on tuples. Here are some examples:\n```\n\u003e\u003e\u003e t = (1, 2, 3)\n\u003e\u003e\u003e max(t)\n\u003e\u003e\u003e 3\n```\n\n## Dicts\n\nA dictionary is a sequence of items. Each item is a pair made of a key and a value. Dictionaries are not sorted. You can access to the list of keys or values independently.\n```\n\u003e\u003e\u003e d = {'first':'string value', 'second':[1,2]}\n\u003e\u003e\u003e d.keys()\n['first', 'second']\n\u003e\u003e\u003e d.values()\n['string value', [1, 2]]\n```\nYou can access to the value of a given key as follows:\n```\n\u003e\u003e\u003e d['first']\n'string value'\n```\n\u003eWarning\n\u003e\n\u003eYou can not have duplicate keys in a dictionary\n\n\u003eWarning\n\u003e\n\u003edictionary have no concept of order among elements\n\n###  Methods to query information\n\nIn addition to keys and values methods, there is also the items method that returns a list of items of the form (key, value). The items are not returned in any particular order:\n```\n\u003e\u003e\u003e d = {'first':'string value', 'second':[1,2]}\n\u003e\u003e\u003e d.items()\n[('a', 'string value'), ('b', [1, 2])]\n```\nThe iteritems method works in much the same way, but returns an iterator instead of a list. See iterators section for an example.\n\nYou can check for the existence of a specific key with has_key:\n```\n\u003e\u003e\u003e d.has_key('first')\nTrue\n```\nThe expression d.has_key(k) is equivalent to k in d. The choice of which to use is largely a matter of taste.\n\nIn order to get the value corresponding to a specific key, use get or pop:\n```\n\u003e\u003e\u003e d.get('first')  # this method can set an optional value, if the key is not found\n'string value'\n```\nIt is useful for things like adding up numbers:\n```\nsum[value] = sum.get(value, 0) + 1\n```\n\nThe difference between get and pop is that pop also removes the corresponding item from the dictionary:\n```\n\u003e\u003e\u003e d.pop('first')\n'string value'\n\u003e\u003e\u003e d\n{'second': [1, 2]}\n```\nFinally, popitem removes and returns a pair (key, value); you do not choose which one because a dictionary is not sorted\n```\n\u003e\u003e\u003e d.popitem()\n('a', 'string value')\n\u003e\u003e\u003e d\n{'second': [1, 2]}\n```\n###  Methods to create new dictionary\n\nSince dictionaries (like other sequences) are objects, you should be careful when using the affectation sign:\n```\n\u003e\u003e\u003e d1 = {'a': [1,2]}\n\u003e\u003e\u003e d2 = d1\n\u003e\u003e\u003e d2['a'] = [1,2,3,4]\n\u003e\u003e\u003e d1['a]\n[1,2,3,4]\n```\nTo create a new object, use the copy method (shallow copy):\n```\n\u003e\u003e\u003e d2 = d1.copy()\n```\nYou can clear a dictionary (i.e., remove all its items) using the clear() method:\n```\n\u003e\u003e\u003e d2.clear()\n{}\n```\nThe clear() method deletes all items whereas del() deletes just one:\n```\n\u003e\u003e\u003e d = {'a':1, 'b':2, 'c':3}\n\u003e\u003e\u003e del d['a']\n\u003e\u003e\u003e d.clear()\n```\nCreate a new item with default value (if not provided, None is the default):\n```\n\u003e\u003e\u003e d2.setdefault('third', '')\n\u003e\u003e\u003e d2['third']\n''\n```\nCreate a dictionary given a set of keys:\n```\n\u003e\u003e\u003e d2.fromkeys(['first', 'second'])\n```\nanother syntax is to start from an empty dictionary:\n```\n\u003e\u003e\u003e {}.fromkeys(['first', 'second'])\n{'first': None, 'second': None}\n```\nJust keep in ,ind thqt the fromkeys() method creates a new dictionary with the given keys, each with a default corresponding value of None.\n\n#### Combining dictionaries\n\nGiven 2 dictionaries d1 and d2, you can add all pairs of key/value from d2 into d1 by using the update method (instead of looping and assigning each pair yourself:\n```\n\u003e\u003e\u003e d1 = {'a':1}\n\u003e\u003e\u003e d2 = {'a':2; 'b':2}\n\u003e\u003e\u003e d1.update(d2)\n\u003e\u003e\u003e d1['a']\n2\n\u003e\u003e\u003e d2['b']\n2\n```\nThe items in the supplied dictionary are added to the old one, overwriting any items there with the same keys.\n\n### iterators\n\nDictionary provides iterators over values, keys or items:\n```\n\u003e\u003e\u003e [x for x in t.itervalues()]\n['string value', [1, 2]]\n\u003e\u003e\u003e\n\u003e\u003e\u003e [x for x in t.iterkeys()]\n['first', 'csecond']\n\u003e\u003e\u003e [x for x in t.iteritems()]\n[('a', 'string value'), ('b', [1, 2])]\n```\nSee also\n\n### Views\n\nviewkeys, viewvalues, viewitems are set-like objects providing a view on D’s keys, values or items.\n\n### comparison\n\nyou can compare dictionaries! Python first compares the sorted key-value pairs. It first sorts dictionaries by key and comapre their initial items. If the items hae different values, Python figures out the comparison between them. Otherwise, the second items are compared and so on.\n\n## Strings\n\nIn short, strings are immutable sequence of characters. There are a lot  of methods to ease manipulation and creation of strings as shown here  below.\n\n### Creating a string (and special characters)\n\nSingle and double quotes are special characters. There are used to defined  strings. There are actually 3 ways to define a string using either  single, double or triple quotes:\n\n```\ntext = 'The surface of the circle is 2 pi R = '\ntext = \"The surface of the circle is 2 pi R = \"\ntext = '''The surface of the circle is 2 pi R = '''\n```\n\nIn fact the latest is generally written using triple double quotes:\n\n```\ntext = \"\"\"The surface of the circle is 2 pi R = \"\"\"\n```\n\nStrings in double quotes work exactly the same as in single quotes but allow to insert single quote character inside them.\n\nThe interest of the triple quotes (‘’’ or “””) is that you can  specify multi-line strings. Moreover, single quotes and double quotes  can be used freely within the triple quotes:\n\n```\ntext = \"\"\" a string with special character \" and ' inside \"\"\"\n```\n\nThe ” and ‘ characters are part of the Python language; they are  special characters. To insert them in a string, you have to escape them  (i.e., with a \\ chracter in front of them to indicate the special nature of the character). For instance:\n\n```\ntext = \" a string with escaped special character \\\", \\' inside \"\n```\n\nThere are a few other special characters that must be escaped to be included in a string. See [*The print statement*](http://docs.python.org/reference/simple_stmts.html#print) for more information.\n\nTo include unicode, you must precede the string with the **u** character:\n\n```\n\u003e\u003e\u003e u\"\\u0041\"\nA\n```\n\nNote\n\nunicode is a single character set used to represent 65536 different characters.\n\nSimilarly, you may see strings preceded by the **r** character to indicate that the string has to be interpreted as it is without interpreting the special character **\\**. This is useful for docstrings that contain latex code for instance:\n\n```\nr\" \\textbf{this is bold text in LaTeX} \"\n```\n\n### Strings are immutable\n\nYou can access to any character using slicing:\n\n```\ntext[0]\ntext[-1]\ntext[0:]\n```\n\nHowever, you cannot change any character:\n\n```\ntext[0] = 'a' #this is incorrect.\n```\n\n### Formatter\n\nIn Python, the % sign lets you produce formatted output. A quick example will illustrate how to print a formatted string:\n\n```\n\u003e\u003e\u003e print(\"%s\" % \"some text\")\n\"some text\"\n```\n\nThe syntax is simply:\n\n```\nstring % values\n```\n\nIf you have more than one value, they should be placed within brackets:\n\n```\n\u003e\u003e\u003e print(\"%s %s\" % (\"a\", \"b\"))\n```\n\nThe string contains characters and *conversion specifiers* (here %s)\n\nTo escape the sign %, just double it:\n\n```\n\u003e\u003e\u003e print \"This is a percent sign: %%\"\nThis is a percent sign: %\n```\n\nThere are different ways of formatting a string with arguments. The one based on a string method called [`format()`](http://docs.python.org/library/stdtypes.html#str.format) is more and more common:\n\n```\n\u003e\u003e\u003e \"{a}!={b}\".format(a=2, b=1)\n2!=1\n```\n\n### Operators\n\nThe mathematical operators `+` and `*` can be used to create new strings:\n\n```\nt = 'This is a test'\nt2 = t+t\nt3 = t*3\n```\n\nand comparison operators `\u003e`, `\u003e=`, `==`,  `\u003c=`, `\u003c` and `!=` can be used to compare strings.\n\n### Methods\n\nThe string methods are numerous, however, many of them are similar (as you will see in this page).\n\n#### Methods to query information\n\nThere are a few methods to check the type of alpha numeric characters present in a string: [`isdigit()`](http://docs.python.org/library/stdtypes.html#str.isdigit), [`isalpha()`](http://docs.python.org/library/stdtypes.html#str.isalpha), [`islower()`](http://docs.python.org/library/stdtypes.html#str.islower), [`isupper()`](http://docs.python.org/library/stdtypes.html#str.isupper), [`istitle()`](http://docs.python.org/library/stdtypes.html#str.istitle), [`isspace()`](http://docs.python.org/library/stdtypes.html#str.isspace), [`str.isalnum()`](http://docs.python.org/library/stdtypes.html#str.isalnum):\n\n```\n\u003e\u003e\u003e \"44\".isdigit()  # is the string made of digits only ?\nTrue\n\u003e\u003e\u003e \"44\".isalpha()  # is the string made of alphabetic characters only ?\nFalse\n\u003e\u003e\u003e \"44\".isalnum()  # is the string made of alphabetic characters or digits only ?\nTrue\n\u003e\u003e\u003e \"Aa\".isupper()  # is it made of upper cases only ?\nFalse\n\u003e\u003e\u003e \"aa\".islower()  # or lower cases only ?\nTrue\n\u003e\u003e\u003e \"Aa\".istitle()  # does the string start with a capital letter ?\nTrue\n\u003e\u003e\u003e text = \"There are spaces but not only\"\n\u003e\u003e\u003e text.isspace() # is the string made of spaces only ?\nFalse\n```\n\nYou can count the occurence of a character with [`count()`](http://docs.python.org/library/stdtypes.html#str.count) or get the length of a string with [`len()`](http://docs.python.org/library/functions.html#len):\n\n```\n\u003e\u003e\u003e mystr = \"This is a string\"\n\u003e\u003e\u003e mystr.count('i')\n3\n\u003e\u003e\u003e len(mystr)\n16\n```\n\n#### Methods that return a modified version of the string\n\nThe following methods return modified copy of the original string, which is immutable.\n\nFirst, you can modify the cases using [`title()`](http://docs.python.org/library/stdtypes.html#str.title), [`capitalize()`](http://docs.python.org/library/stdtypes.html#str.capitalize), [`lower()`](http://docs.python.org/library/stdtypes.html#str.lower), [`upper()`](http://docs.python.org/library/stdtypes.html#str.upper) and [`swapcase()`](http://docs.python.org/library/stdtypes.html#str.swapcase):\n\n```\n\u003e\u003e\u003e mystr = \"this is a dummy string\"\n\u003e\u003e\u003e mystr.title()       # return a titlecase version of the string\n'This Is A Dummy String'\n\u003e\u003e\u003e mystr.capitalize()  # return a string with first letter capitalised only.\n'This is a dummy string'\n\u003e\u003e\u003e mystr.upper()       # return a capitalised version of the string\n'THIS IS A DUMMY STRING'\n\u003e\u003e\u003e mystr.lower()       # return a copy of the string converted to lower case\n'this is a dummy string'\n\u003e\u003e\u003e mystr.swapcase()    # replace lower case by upper case and vice versa\n'THIS IS A DUMMY STRING'\n```\n\nSecond, you can add trailing characters with [`center()`](http://docs.python.org/library/stdtypes.html#str.center) and `just()` methods:\n\n```\n\u003e\u003e\u003e mystr = \"this is a dummy string\"\n\u003e\u003e\u003e mystr.center(40)              # center the string in a string of length 40\n'         this is a dummy string         '\n\u003e\u003e\u003e mystr.ljust(30)               # justify the string to the left (width of 20)\n'this is a dummy string        '\n\u003e\u003e\u003e mystr.rjust(30, '-')          # justify the string to the right (width of 20)\n'--------this is a dummy string'\n```\n\nThere is also a [`zfill()`](http://docs.python.org/library/stdtypes.html#str.zfill) methods that adds zero to the left, which is equivalent to `.rjust(width, '0')`:\n\n```\n\u003e\u003e\u003e mystr.zfill(30)\n'00000000this is a dummy string'\n```\n\nor remove trailing spaces with the [`strip()`](http://docs.python.org/library/stdtypes.html#str.strip) methods:\n\n```\n\u003e\u003e\u003e mystr = \"  string with left and right spaces   \"\n\u003e\u003e\u003e mystr.strip()\n'string with left and right spaces'\n\u003e\u003e\u003e mystr.rstrip()\n'  string with left and right spaces'\n\u003e\u003e\u003e mystr.lstrip()\n'string with left and right spaces   '\n```\n\nor expand tabs with [`expandtabs()`](http://docs.python.org/library/stdtypes.html#str.expandtabs):\n\n```\n\u003e\u003e\u003e 'this is a \\t tab'.expandtabs()\n'this is a     tab'\n```\n\nYou can remove some specific characters with [`translate()`](http://docs.python.org/library/stdtypes.html#str.translate) or replace words with [`replace()`](http://docs.python.org/library/stdtypes.html#str.replace):\n\n```\n\u003e\u003e\u003e mystr = \"this is a dummy string\"\n\u003e\u003e\u003e mystr.replace('dummy', 'great', 1)  # the 1 means replace only once\n'this is a great string'\n\u003e\u003e\u003e mystr.translate(None, 'aeiou')\nths s dmmy strng\n```\n\nFinally, you can separate a string with respect to a single separator with [`partition()`](http://docs.python.org/library/stdtypes.html#str.partition):\n\n```\n\u003e\u003e\u003e mystr = \"this is a dummy string\"\n\u003e\u003e\u003e t.partition('is')\n('th', 'is', ' is a line')\n\u003e\u003e\u003e t.rpartition('is')\n('this ', 'is', ' a line')\n```\n\n#### Methods to find position of substrings\n\nThe are methods such as [`endswith()`](http://docs.python.org/library/stdtypes.html#str.endswith), [`startswith()`](http://docs.python.org/library/stdtypes.html#str.startswith), [`find()`](http://docs.python.org/library/stdtypes.html#str.find) and [`index()`](http://docs.python.org/library/stdtypes.html#str.index) that allow to search for substrings in a string.\n\n```\n\u003e\u003e\u003e mystr = \"This is a dummy string\"\n\u003e\u003e\u003e mystr.endswith('ing')       # may provide optional start and end indices\nTrue\n\u003e\u003e\u003e mystr.startswith('This')    # may provide start and end indices\nTrue\n\u003e\u003e\u003e mystr.find('is')            # returns start index of 'is' first occurence\n2\n\u003e\u003e\u003e mystr.find('is', 4)         # starting at index 4, returns start index of 'is' first occurence\n5\n\u003e\u003e\u003e mystr.rfind('is')           # returns start index of 'is' last occurence\n5\n\u003e\u003e\u003e mystr.index('is')           # like find but raises error when substring is not found\n2\n\u003e\u003e\u003e mystr.rindex('is')          # like rfind but raises error when substring is not found\n5\n```\n\n#### Methods to build or decompose a string\n\nA useful function is the [`split()`](http://docs.python.org/library/stdtypes.html#str.split) methods that splits a string according to a character. The inverse function exist and is called [`join()`](http://docs.python.org/library/stdtypes.html#str.join).\n\n```\n\u003e\u003e\u003e message = ' '.join(['this' ,'is', 'a', 'useful', 'method'])\n\u003e\u003e\u003e message\n'this is a useful method'\n\u003e\u003e\u003e message.split(' ')\n['this', 'is', 'a', 'useful', 'method']\n```\n\nThe [`split()`](http://docs.python.org/library/stdtypes.html#str.split) function can be applied to a limited number of times if needed.  However, it starts from the left. If you want to start from the right,  use [`rsplit()`](http://docs.python.org/library/stdtypes.html#str.rsplit) instead:\n\n```\n\u003e\u003e\u003e message = ' '.join(['this' ,'is', 'a', 'useful', 'method'])\n\u003e\u003e\u003e message.rsplit(' ', 2)\n['this is a', 'useful', 'method']\n```\n\nIf a string is multi-lines, you can split it with [`splitlines()`](http://docs.python.org/library/stdtypes.html#str.splitlines):\n\n```\n\u003e\u003e\u003e 'this is an example\\n of\\ndummy sentences'.splitlines()\n['this is an example', ' of', 'dummy sentences']\n```\n\nyou can keep the endline character by giving True as an optional argument.\n\nFinally, note that [`split()`](http://docs.python.org/library/stdtypes.html#str.split) removes the splitter:\n\n```\n\u003e\u003e\u003e \"this is an exemple\".split(\" is \")\n['this', 'an exemple']\n```\n\nIf you want to keep the splitter as well, use [`partition()`](http://docs.python.org/library/stdtypes.html#str.partition)\n\n```\n\u003e\u003e\u003e \"this is an exemple\".partition(\" is \")\n('this', ' is ', 'an exemple')\n```\n\n#### Encoding/Decoding/Unicode\n\nWe’ve seen how to create a unicode by adding the letter **u** in front of a string:\n\n```\ns = u\"\\u0041\"\n```\n\nThe function [`unicode()`](http://docs.python.org/library/functions.html#unicode) converts a standard string to unicode string using the encoding  specified as an argument (default is the default string encoding):\n\n```\ns = unicode(\"text\", \"ascii\")\n```\n\nIn order to figure out the default encoding, type:\n\n```\n\u003e\u003e\u003e import sys\n\u003e\u003e\u003e sys.getdefaultencoding()\n'ascii'\n```\n\nHere are some encodings:\n\n```\nascii, utf-8, iso-8859-1, latin-1, utf-16, unicode-escape.\n```\n\nThe unicode function takes also a third argument set to: ‘strict’, ‘ignore’ or ‘replace’.\n\nLet us take another example with accents:\n\n```\n\u003e\u003e\u003e # Let us start wil a special character.\n\u003e\u003e\u003e text = u\"π\"\n\u003e\u003e\u003e # to obtain its code (in utf-8), let us use the encode function\n\u003e\u003e\u003e encoded = text.encode(\"utf-8\")\n\u003e\u003e\u003e decoded = text.decode(\"utf-8\")\n```\n\n## Sets\n\nSets are constructed from a sequence (or some other iterable object).  Since sets cannot have duplicated, there are usually used to build  sequence of unique items (e.g., set of identifiers).\n\n\n###  Quick example\n```\n\u003e\u003e\u003e a = set([1, 2, 3, 4])\n\u003e\u003e\u003e b = set([3, 4, 5, 6])\n\u003e\u003e\u003e a | b # Union\n{1, 2, 3, 4, 5, 6}\n\u003e\u003e\u003e a \u0026 b # Intersection\n{3, 4}\n\u003e\u003e\u003e a \u003c b # Subset\nFalse\n\u003e\u003e\u003e a - b # Difference\n{1, 2}\n\u003e\u003e\u003e a ^ b # Symmetric Difference\n{1, 2, 5, 6}\n```\n\u003eNote\n\u003e\n\u003ethe intersection, subset, difference and symmetric difference can be be called with method rather that symbols. See below for examples.\n\n### Ordering\n\nJust as with dictionaries, the ordering of set elements is quite arbitrary, and shouldn’t be relied on.\n\n### Operators\n\nAs mentionned in the quick example section, each operator is associated to a symbol (e.g., \u0026) and a method name (e.g. union).\n```\n\u003e\u003e\u003e a = set([1, 2, 3])\n\u003e\u003e\u003e b = set([2, 3, 4])\n\u003e\u003e\u003e c = a.intersection(b) # equivalent to c = a \u0026 b\n\u003e\u003e\u003e a.intersection(b)\nset([2, 3])\n```\n```\n\u003e\u003e\u003e c.issubset(a)\nTrue\n\u003e\u003e\u003e c \u003c= a\nTrue\n```\n```\n\u003e\u003e\u003e c.issuperset(a)\nFalse\n\u003e\u003e\u003e c \u003e= a\nFalse\n```\n```\n\u003e\u003e\u003e a.difference(b)\nset([1])\n\u003e\u003e\u003e a - b\nset([1])\n```\n```\n\u003e\u003e\u003e a.symmetric_difference(b)\nset([1, 4])\n\u003e\u003e\u003e a ^ b\nset([1, 4])\n```\nYou can also copy a set using the copy method:\n```\n\u003e\u003e\u003e a.copy()\nset([1, 2, 3])\n```\n## Frozensets\n\nSets are mutable, and may therefore not be used, for example, as keys in dictionaries.\n\nAnother problem is that sets themselves may only contain immutable (hashable) values, and thus may not contain other sets.\n\nBecause sets of sets often occur in practice, there is the frozenset type, which represents immutable (and, therefore, hashable) sets.\n\n### Quick Example\n```\n\u003e\u003e\u003e a = frozenset([1, 2, 3])\n\u003e\u003e\u003e b = frozenset([2, 3, 4])\n\u003e\u003e\u003e a.union(b)\nfrozenset([1, 2, 3, 4])\n```\n### Set of Sets\n\nSets may only contain immutable (hashable) values, and thus may not contain other sets, in which case frozensets can be useful. Consider the following example:\n```\n\u003e\u003e\u003e a = set([1, 2, 3])\n\u003e\u003e\u003e b = set([2, 3, 4])\n\u003e\u003e\u003e a.add(b)\n\u003e\u003e\u003e a.add(frozenset(b))\n```\n### Using set as key in a dictionary\n\nIf you want to use a set as a key dictionary, you will need frozenset:\n```\n\u003e\u003e\u003e fa = {frozenset([1,2]): 1}\n\u003e\u003e\u003e fa[ frozenset([1,2]) ]\n1\n```\n### Methods\n\nfrozensets have less methods than sets.\n\nThere are some operators similar to sets (intersection(), union(), symmetric_difference(), difference(), issubset(), isdisjoint(), issuperset()) and a copy() method.\n\n## The collections module\nThe collections module provides additional data structure. For now, we’ll look at the deque data structure. Consider also the OrderedDict class, which is similar to a dictionary but with keys being ordered.\n### Deque: double-ended queues\n\nDouble-ended queues, or deques, can be useful when you need to remove elements in the order in which they were added. You can find the deque functions in the collections module.\n```\n\u003e\u003e\u003e from collections import deque\n\u003e\u003e\u003e q = deque(range(5))\n\u003e\u003e\u003e q.append(5)\n\u003e\u003e\u003e q.appendleft(6)\n\u003e\u003e\u003e q \ndeque([6, 0, 1, 2, 3, 4, 5])\n\u003e\u003e\u003e q.pop()\n5\n\u003e\u003e\u003e q.popleft()\n6\n\u003e\u003e\u003e q.rotate(3)\n\u003e\u003e\u003e q \ndeque([2, 3, 4, 0, 1])\n```\nThe reason for the usefulness of the deque is that it allows appending and popping efficiently at the beginning (to the left), as opposed to lists. As a nice side effect, you can also rotate the elements (that is, shift them to the right or left, wrapping around the ends) efficiently. Deque objects also have extend and extendleft methods, with extend working like the corresponding list method, and extendleft working analogously to appendleft. Note that the elements in the iterable used in extendleft will appear in the deque in reverse order.\n\n### Named Tuples\n\nSometimes, it is convenient to access to a mutable element by its names rather than an index. This is possible with the collections.namedtuple() function. Your first need to design a structure using namedtuple function. Then, you create the named tuple.\n```\nperson = collections.namedtuple(\"FirstName\", \"Surname\", \"age\")\npersons = []\npersons.append(person(\"Alain\", \"Delon\", 32))\npersons.append(person(\"Jean\", \"Gabin\", 39))\n```\nYou can now access to the first names of each tuple using the name attribute:\n```\nfirst_names = [x.name for x in persons]\n```\n## The heapq module\nA priority queue lets you add objects in an arbitrary order and at any time (possibly in-between the adding) find (and possibly remove) the smallest element. It does so much more efficiently than, say, using min on a list.\n\nThe heapq module (with the q standing for queue) contains six functions, the first four of which are directly related to heap manipulation. You must use a list as the heap object itself.\n\nThe heappush function is used to add an item to a heap. Note that you shouldn’t use it on any old list–only one that has been built through the use of the various heap functions. The reason for this is that the order of the elements is important.\n```\n\u003e\u003e\u003e from heapq import *\n\u003e\u003e\u003e from random import shuffle\n\u003e\u003e\u003e data = range(10)\n\u003e\u003e\u003e shuffle(data)\n\u003e\u003e\u003e heap = []\n\u003e\u003e\u003e for n in data:\n...     heappush(heap, n)\n\u003e\u003e\u003e heap \n[0, 1, 3, 6, 2, 8, 4, 7, 9, 5]\n\u003e\u003e\u003e heappush(heap, 0.5)\n\u003e\u003e\u003e heap \n[0, 0.5, 3, 6, 1, 8, 4, 7, 9, 5, 2]\n```\n\u003eNote\n\u003e\n\u003eThe order of the elements isn’t as arbitrary as it seems. They aren’t in strictly sorted order, but there is one guarantee made: the element at position i is always greater than the one in position i // 2. This is the basis for the underlying heap algorithm. This is called the heap property.\n\nThe heappop function pops off the smallest element, which is always found at index 0, and makes sure that the smallest of the remaining element takes over this position:\n```\n\u003e\u003e\u003e heappop(heap)\n0\n\u003e\u003e\u003e heappop(heap)\n0.5\n\u003e\u003e\u003e heappop(heap)\n1\n\u003e\u003e\u003e heap \n[2, 5, 3, 6, 9, 8, 4, 7]\n```\n\u003eNote \n\u003e\n\u003eThe method heappushpop that pushes item on the heap, then pops and returns the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop().\n\nThe heapify function takes an arbitrary list and makes it a heap:\n```\n\u003e\u003e\u003e heap = [5, 8, 0, 3, 6, 7, 9, 1, 4, 2]\n\u003e\u003e\u003e heapify(heap)\n\u003e\u003e\u003e heap \n[0, 1, 5, 3, 2, 7, 9, 8, 4, 6]\n```\nThe heapreplace function is not quite as commonly used as the others. It pops the smallest element off the heap and then pushes a new element onto it. This is more efficient than a heappop followed by a heappush:\n```\n\u003e\u003e\u003e heapreplace(heap, 0.5)\n0\n\u003e\u003e\u003e heap \n[0, 0.5, 3, 4, 1, 6, 8, 9, 7, 5, 2]\n\u003e\u003e\u003e heapreplace(heap, 10)\n0.5\n\u003e\u003e\u003e heap \n[1, 2, 5, 3, 6, 7, 9, 8, 4, 10]\n```\nThe remaining two functions of the heapq module, nlargest(n, iter) and nsmallest(n, iter), are used to find the n largest or smallest elements, respectively, of any iterable object iter. You could do this by using sorting (for example, using the sorted function) and slicing, but the heap algorithm is faster and more memory-efficient (and, not to mention, easier to use).\n\n### Other Methods\nLike list, there is a count() method to count occurences of an item.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbeangreen247%2Fdata-structures-in-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbeangreen247%2Fdata-structures-in-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbeangreen247%2Fdata-structures-in-python/lists"}