{"id":20959218,"url":"https://github.com/codophobia/python-code-snippets","last_synced_at":"2025-09-25T18:26:35.985Z","repository":{"id":119766377,"uuid":"489974597","full_name":"codophobia/python-code-snippets","owner":"codophobia","description":"Code snippets on how to use different features in Python 3","archived":false,"fork":false,"pushed_at":"2022-05-12T20:27:13.000Z","size":3,"stargazers_count":32,"open_issues_count":1,"forks_count":13,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-05-31T00:30:14.980Z","etag":null,"topics":["code","examples-python","libraries","programming","python","python3"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codophobia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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":"2022-05-08T14:59:53.000Z","updated_at":"2023-04-21T04:32:15.000Z","dependencies_parsed_at":null,"dependency_job_id":"64377994-f1e8-4bd9-a74a-96c55a3d9942","html_url":"https://github.com/codophobia/python-code-snippets","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/codophobia/python-code-snippets","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codophobia%2Fpython-code-snippets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codophobia%2Fpython-code-snippets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codophobia%2Fpython-code-snippets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codophobia%2Fpython-code-snippets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codophobia","download_url":"https://codeload.github.com/codophobia/python-code-snippets/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codophobia%2Fpython-code-snippets/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276966304,"owners_count":25736755,"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","status":"online","status_checked_at":"2025-09-25T02:00:09.612Z","response_time":80,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["code","examples-python","libraries","programming","python","python3"],"created_at":"2024-11-19T01:52:15.482Z","updated_at":"2025-09-25T18:26:35.979Z","avatar_url":"https://github.com/codophobia.png","language":null,"readme":"# Python Code Snippets\n \n \n## List\n \n```python\n# Create a list and iterate over it\n \nnumbers = []\nnumbers.append(1)\nnumbers.append(2)\nnumbers.append(3)\n \nfor num in numbers:\n  print(num)\n \n'''\n1\n2\n3\n'''\n```\n \n```python\n# Create a list and iterate over it\n \nnumbers = [1, 2, 3]\nlength = len(numbers)\nfor i in range(length):\n  print(numbers[i])\n \n# Output\n'''\n1\n2\n3\n'''\n```\n \n```python\n# Modify values in a list\n \nnumbers = [1, 2, 3]\nfor i in range(len(numbers)):\n   numbers[i] += 1\nprint(numbers)\n \n'''\n[2, 3, 4]\n'''\n```\n \n```python\n# Sort a list in-place in ascending order\n \na = [2, 4, 1, 9, 8]\na.sort()\nprint(a)\n \n'''\n[1, 2, 4, 8, 9]\n'''\n```\n \n```python\n# Sort a list in-place in descending order\n \na = [2, 4, 1, 9, 8]\na.sort(reverse = True)\nprint(a)\n \n'''\n[9, 8, 4, 2, 1]\n'''\n```\n \n## Strings\n \n```python\n# Declare a string and iterate over the characters\n \nstring = 'Hello'\nfor c in string:\n  print(c)\n \n'''\nH\ne\nl\nl\no\n'''\n```\n \n```python\n# Declare a string and iterate over the characters\n \nstring = 'Hello'\nfor i in range(len(string)):\n  print(string[i])\n \n'''\nH\ne\nl\nl\no\n'''\n```\n \n```python\n# Modifying a string\n \nstring = 'hello'\nstring[0] = 'H'\n \n'''\nTypeError: 'str' object does not support item assignment\n'''\n```\n \n```python\n# Sort a string\n \ns = 'shivam'\nsorted_s = ''.join(sorted(s))\nprint(sorted_s)\n \n'''\nahimsv\n'''\n```\n \n \n## Tuples\n \n```python\n# Declare a tuple and iterate over it\n \nvowels = ('a', 'e', 'i', 'o', 'u')\nfor v in vowels:\n   print(v)\n \n'''\na\ne\ni\no\nu\n'''\n```\n \n```python\n# Declare a tuple and print elements\n \nvowels = ('a', 'e', 'i', 'o', 'u')\nprint(vowels[0])\nprint(vowels[2])\nprint(vowels[-1])\n \n'''\na\ni\nu\n'''\n```\n \n```python\n# Modify a tuple\n \nvowels = ('a', 'e', 'i', 'o', 'u')\nvowels[0] = 'b'\n \n'''\nTypeError: 'tuple' object does not support item assignment\n'''\n```\n \n## Dictionary\n \n```python\n# Declare a dictionary and print key value pairs\n \nd = {'1': 'Dhoni', '2': 'Sachin', '3': 'Dravid'}\n \nfor k,v in d.items():\n  print(k,v)\n \n'''\n1 Dhoni\n2 Sachin\n3 Dravid\n'''\n```\n \n```python\n# Dynamically insert key values and print it\n \nd = {}\n \n# Store square of numbers from 1 to 5\nfor i in range(1, 6):\n  d[i] = i*i\n \n# Print the square\nfor k,v in d.items():\n  print(k,v)\n \n# Output\n'''\n1 1\n2 4\n3 9\n4 16\n5 25\n'''\n```\n \n## Set\n \n```python\n# Declare a set, insert values and print it\n \ns = set()\ns.add(1)\ns.add(4)\ns.add(3)\ns.add(1)\nprint(s)\n \n'''\n{1, 3, 4}\n'''\n```\n \n## 2D list/array\n \n```python\n# Declare a 2D list\n \nN = 5\nM = 5\n \nmatrix = [0]*N\nfor i in range(N):\n   col = [0]*M\n   matrix[i] = col\nprint(matrix)\n \n'''\n[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]\n'''\n```\n \n```python\n# Declare a 2D list\n \nN = 5\nM = 5\n \nmatrix = [[0 for j in range(M)] for i in range(N)]\nprint(matrix)\n \n'''\n[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]\n'''\n```\n \n```python\n# Declare a 2D list\n \nN = 5\nM = 5\n \nmatrix = [[0]*M for i in range(N)]\nprint(matrix)\n \n'''\n[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]\n'''\n```\n \n```python\n# Modify the values in a 2D list\n \nmatrix = [[0]*4 for i in range(3)]\nfor i in range(3):\n   for j in range(4):\n       matrix[i][j] += 1\nprint(matrix)\n \n'''\n[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n'''\n```\n \n## Deque\n \n```python\n# Operations on deque\n \nfrom collections import deque\n \ndq = deque([])\ndq.append(1)\ndq.append(2)\ndq.appendleft(3)\ndq.appendleft(4)\nprint(dq)\nprint(dq.pop())\nprint(dq.popleft())\n \n'''\ndeque([4, 3, 1, 2])\n2\n4\n'''\n```\n \n## Queue\n \n```python\n# Implement queue using deque\n \nfrom collections import deque\n \nq = deque([])\nq.append(1)\nq.append(2)\nq.append(3)\nprint(q)\nprint(q.popleft())\nprint(q.popleft())\n \n'''\ndeque([1, 2, 3])\n1\n2\n'''\n```\n \n```python\n# Implement queue using Queue\n \nfrom queue import Queue\nq = Queue()\nq.put(1)\nq.put(2)\nq.put(2)\nprint(q.qsize())\nprint(q.get())\nprint(q.get())\nprint(q.qsize())\n \n'''\n3\n1\n2\n1\n'''\n```\n \n## Stack\n \n```python\n# Implement stack using list\n \nstack = []\nstack.append(1)\nstack.append(2)\nstack.append(3)\n \nprint(stack)\nprint(stack.pop())\nprint(stack.pop())\nprint(stack)\n \n'''\n[1, 2, 3]\n3\n2\n[1]\n'''\n```\n \n```python\n# Implement stack using deque\n \nfrom collections import deque\n \nstack = deque([])\nstack.append(1)\nstack.append(2)\nstack.append(3)\n \nprint(stack)\nprint(stack.pop())\nprint(stack.pop())\nprint(stack)\n \n'''\ndeque([1, 2, 3])\n3\n2\ndeque([1])\n'''\n```\n \n## Ordered dictionary\n \n```python\n# Operations on ordereddict\n \nfrom collections import OrderedDict\n \nd = OrderedDict()\nd[1] = 2\nd[2] = 3\nd[3] = 4\n \n# If we print the dictionary now, the keys will be printed in order of insertion.\nfor k,v in d.items():\n  print(k,v)\n \nprint(d.popitem(last=False))\nprint(d.popitem())\n \n'''\n1 2\n2 3\n3 4\n(1, 2)\n(3, 4)\n'''\n```\n \n## Defaultdict\n \n```python\n# Operations on defaultdict\n \nfrom collections import defaultdict\n \nnumbers = [1, 1, 2, 5, 2, 8]\nd = defaultdict(int)\n \nfor num in numbers:\n   d[num] += 1\n \nfor k,v in d.items():\n   print(k, v)\n \n'''\n1 2\n2 2\n5 1\n8 1\n'''\n```\n \n## Counters\n \n```python\nfrom collections import Counter\n \nnumbers = [1, 1, 2, 5, 2, 8]\ncntr = Counter(numbers)\n \nfor k,v in cntr.items():\n   print(k, v)\n \n'''\n1 2\n2 2\n5 1\n8 1\n'''\n```\n \n## Namedtuples\n \n```python\nfrom collections import namedtuple\n \nPoint = namedtuple('Point', ['x', 'y'])\np1 = Point(1, 2)\nprint(p1.x, p1.y)\n \n'''\n1 2\n'''\n```\n \n## Heaps\n \n```python\n# Min heap usage\n \nimport heapq\n \nL = []\nheapq.heapify(L) # Min heap\nheapq.heappush(L, 3) # Pushing 3 into heap\nheapq.heappush(L, 2) # Pushing 2 into heap\nprint(L)\nprint(heapq.heappop(L)) # Popping the minimum element\nprint(L)\n \n'''\n[2, 3]\n2\n[3]\n'''\n```\n \n## Binary search\n \n```python\n# Check if an elements is present or not and return the index if element is present\n \nfrom bisect import bisect_left\na = [1, 2, 4, 4, 5]\nx = 4\nidx = bisect_left(a, x)\nif idx != len(a) and a[idx] == x:\n   print(f'{x} is present at index {idx}')\nelse:\n   print('Element not found')\n \n'''\n4 is present at index 2\n'''\n```\n \n```python\n# Find index of first element greater than or equal to target(x)\n \nfrom bisect import bisect_left\na = [1, 2, 4, 4, 5]\nx = 6\nidx = bisect_left(a, x)\nif idx == len(a):\n   print('All elements are smaller than the target element')\nelse:\n   print(idx)\n \n'''\nAll elements are smaller than the target element\n'''\n```\n \n```python\n# Find index of first element greater than target(x)\n \nfrom bisect import bisect_right\na = [1, 2, 4, 4, 5]\nx = 4\nidx = bisect_right(a, x)\nif idx == len(a):\n   print('All elements are smaller than the target element')\nelse:\n   print(idx)\n \n'''\n4\n'''\n```\n \n## Linked list\n \n```python\n# Create a singly linked list and traverse it\n \nclass Node:\n  def __init__(self, data):\n      self.data = data\n      self.next = None\n \nclass LinkedList:\n  def __init__(self):\n      self.head = None\n   def insert_at_end(self, data):\n      new_node = Node(data)\n      if self.head is None:\n          self.head = new_node\n      else:\n          temp = self.head\n          while(temp.next):\n              temp = temp.next\n          temp.next = new_node\n   def traverse(self):\n      temp = self.head\n      while(temp):\n          print(temp.data)\n          temp = temp.next\n \nll = LinkedList()\nll.insert_at_end(1)\nll.insert_at_end(2)\nll.insert_at_end(3)\nll.traverse()\n \n'''\n1\n2\n3\n'''\n```\n \n## Binary Tree\n \n```python\n# Create a binary tree and traverse it\n \nclass Node:\n  def __init__(self, data):\n      self.data = data\n      self.left = None\n      self.right = None\n \nroot = Node(1)\nroot.left = Node(2)\nroot.right = Node(3)\nroot.left.left = Node(4)\nroot.right.left = Node(5)\n \n# Binary tree created from the above code\n'''\n              1\n             / \\\n            2   3\n           /     \\\n          4       5\n'''\n \ndef inorder(root):\n  if not root:\n      return\n  print(root.data)\n  inorder(root.left)\n  inorder(root.right)\n \ninorder(root)\n \n'''\n1\n2\n4\n3\n5\n'''\n```\n \n## Graph\n \n```python\n# Create a graph and traverse it\n \nfrom collections import defaultdict\n \ngraph = defaultdict(list)\ngraph[1].append(2) # 1 -\u003e 2\ngraph[2].append(3) # 1 -\u003e 2 -\u003e 3\ngraph[4].append(1) # 4 -\u003e 1 -\u003e 2 -\u003e 3\n \nvisited = set()\n \ndef dfs(node, graph, visited):\n  if node not in visited:\n      print(node)\n      visited.add(node)\n      for v in graph[node]:\n          dfs(v, graph, visited)\n \ndfs(4, graph, visited)\n \n'''\n4\n1\n2\n3\n'''\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodophobia%2Fpython-code-snippets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodophobia%2Fpython-code-snippets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodophobia%2Fpython-code-snippets/lists"}