I have a nested python for loop and need to append 2 times a value, is the code below PEP8 valid? Or there is a better pythonic way to to write the function?
def function():
empty_list = []
my_list = ['a', 'b', 'c']
for letter_1 in my_list:
for letter_2 in my_list:
empty_list.append(letter_1)
empty_list.append(letter_2)
return empty_list
CodePudding user response:
Assuming that your desired output is:
Desired output:
['a','a','a','b','a','c', # letter_1, with loop of letter_2
'b','a','b','b','b','c', # letter_2, with loop of letter_2
'c','a','c','b','c','c'] # letter_3, with loop of letter_2
An alternative (more "pythonic"?) way to write your function is to use the itertools library and list comprehensions:
def alt_function(my_list = ['a', 'b', 'c']):
iterable = chain.from_iterable([a b for a, b in product(my_list, repeat=2)])
return list(iterable)
alt_function()
Output
['a','a','a','b','a','c',
'b','a','b','b','b','c',
'c','a','c','b','c','c']
CodePudding user response:
Your code is right and PEP8 compliant. I would remove the my_list
from the function block and make it a function's parameter. I would suggest using list.extend()
to perform the operation you need in one line. In order to make it a bit more Pythonic I would add typing hints and the function's docstring. The code would look like this:
from typing import List
def function(my_list: List) -> List:
"""Function's docstring.
Args:
my_list (List): List of characters.
Returns:
List: Processed list of characters.
"""
empty_list = []
for a in my_list:
for b in my_list:
empty_list.extend((a, b))
return empty_list
I don't know which IDE you use, but on Visual Studio Code you can download some extensions to generate docstrings automatically from your function's/classes' signature and typing hints. And also, there's extensions to automatically lint Python code to be PEP8 compliant.
I would also add a small test to make sure my function works as expected. Something like this:
assert function(['a', 'b', 'c']) == ['a', 'a', 'a', 'b', 'a', 'c',
'b', 'a', 'b', 'b', 'b', 'c', 'c', 'a', 'c', 'b', 'c', 'c']