snippetpythonTip
Initialize lists with values, ranges & dates
Viewed 0 times
rangeslistswithdatespythoninitializevalues
Problem
In order to initialize a list with a specific value, all you need to do is to use a list comprehension and
For a numeric range between
Similarly, for a list with dates between
Finally, for a 2D list, you'll need to use a nested list comprehension to generate a list of lists, where each inner list is initialized with the desired value.
range() to generate a list of length equal to n, filled with the desired values.For a numeric range between
start and end (inclusive), you can use a list comprehension and range() to generate a list of the appropriate length, filled with the desired values in the given range.Similarly, for a list with dates between
start (inclusive) and end (not inclusive), you can use a list comprehension and datetime.timedelta to generate a list of datetime.date objects.Finally, for a 2D list, you'll need to use a nested list comprehension to generate a list of lists, where each inner list is initialized with the desired value.
Solution
def initialize_list_with_values(n, val = 0):
return [val for x in range(n)]
initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]Similarly, for a list with dates between
start (inclusive) and end (not inclusive), you can use a list comprehension and datetime.timedelta to generate a list of datetime.date objects.Finally, for a 2D list, you'll need to use a nested list comprehension to generate a list of lists, where each inner list is initialized with the desired value.
Code Snippets
def initialize_list_with_values(n, val = 0):
return [val for x in range(n)]
initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]def initialize_list_with_range(end, start = 0, step = 1):
return list(range(start, end + 1, step))
initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]
initialize_list_with_range(7, 3) # [3, 4, 5, 6, 7]
initialize_list_with_range(9, 0, 2) # [0, 2, 4, 6, 8]from datetime import timedelta, date
def daterange(start, end):
return [start + timedelta(n) for n in range(int((end - start).days))]
daterange(date(2020, 10, 1), date(2020, 10, 5))
# [date(2020, 10, 1), date(2020, 10, 2), date(2020, 10, 3), date(2020, 10, 4)]Context
From 30-seconds-of-code: initialize-list-with-range-value-daterange
Revisions (0)
No revisions yet.