Skip to content

Instantly share code, notes, and snippets.

@yochem
Last active November 21, 2019 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yochem/c6a513ee23c7c3595180f431edc3f2fd to your computer and use it in GitHub Desktop.
Save yochem/c6a513ee23c7c3595180f431edc3f2fd to your computer and use it in GitHub Desktop.
numbers = [1, 2, 3, 4]
#############################
# general looping
#############################
for i in range(len(numbers)):
print(numbers[i])
# should be
for num in numbers:
print(num)
#############################
# reversed looping
#############################
list_len = len(numbers)
for i in range(list_len):
print(numbers[list_len - i - 1])
# or...
for i in range(list_len - 1, -1, -1):
print(numbers[i])
# should be
for num in reversed(numbers):
print(num)
#############################
# certain range of list
#############################
for i in range(1, 3):
print(numbers[i])
# should be
for num in numbers[1:3]:
print(num)
#############################
# only elements with even indices
#############################
for i in range(len(numbers)):
if i % 2 == 0:
print(numbers[i])
# should be
for num in numbers[::2]:
print(num)
#############################
# including indices
#############################
for i in range(len(numbers)):
print(i, numbers[i])
# should be
for i, num in enumerate(numbers):
print(i, num)
#############################
# two lists at once
#############################
numbers_2 = [5, 6, 7, 8]
for i in range(len(numbers)):
print(numbers[i], numbers_2[i])
# should be
for num_1, num_2 in zip(numbers, numbers_2):
print(num_1, num_2)
#############################
# dictionaries
#############################
data = {'name': 'bob', 'mail': 'bob@bobmail.com', 'address': 'bobstreet 12'}
for key in data:
print(key, data[key])
# should be
for key, value in data.items():
print(key, value)
# bonus
for value in data.values():
print(value)
#############################
# list comprehensions
#############################
x_data = [1, 2, 3, 4]
y_data = []
for x in x_data:
y_data.append(x**2)
# should be
x_data = [1, 2, 3, 4]
y_data = [x**2 for x in x_data]
# bonus
# initialize with 0
names = ['alice', 'bob', 'charlie']
name_count = {name: 0 for name in names}
# convert names to set
names_set = {name for name in names}
# add conditions to comprehension
l_names = [name for name in names if 'l' in name]
pour_bob = [name for name in names if len(name) < 4]
# although easy list comprehensions are really readable,
# they tend to get quite unreadable if they are longer and
# nested, so don't do this:
name = {name: [i for i in range(100) if i != 40] for name in names if
len(name) > 3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment