Skip to content

Instantly share code, notes, and snippets.

@jack-zheng
Last active March 11, 2026 20:58
Show Gist options
  • Select an option

  • Save jack-zheng/ac52aad23a125255011f2eefe5e77372 to your computer and use it in GitHub Desktop.

Select an option

Save jack-zheng/ac52aad23a125255011f2eefe5e77372 to your computer and use it in GitHub Desktop.
pythonic, python

Writing in Pythonic way

This postion is a notebook to collect the pythonic code I fetch when do code research.

Generate random int list, or just a requirement of loop N times

it's a common requirement and some guys achieve this goal by using Numpy lib, but it's too heavy. you can do in this way:

import random

for _ in range(10)
  print(random.randint(0, 100))
  
# the _ is from 0 - 9

Get index and val at the same time

a = ['a','b','c','d'] 
for idx, val in enumerate(a): 
   print(f'idx = {idx}, val = {val}')                                                                                                                  
# Output:
# idx = 0, val = a
# idx = 1, val = b
# idx = 2, val = c
# idx = 3, val = d

if you want to specify the start index, you can add a second parameter to enumerate func

# in this case, idx would start from 3
a = ['a','b','c','d']
for idx, val in enumerate(a, 3):
  print(f'idx = {idx}, val = {val}')
  
# Output:
# idx = 3, val = a
# idx = 4, val = b
# idx = 5, val = c
# idx = 6, val = d
@omarmd314
Copy link

good idea bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment