How to Determine the Next Date From a List in Python
The Python language provides programmers with many ways to handle the collection of information. Data can be stored in lists, arrays, hash tables, tuples and sets. Lists provide a simple and direct way to store, access and modify collections of strings, numbers or a combination of both. Python's datetime object enables retrieval of date information in many different formats. The method datetime.date.today() returns the date as a string in the "yyyy-mm-dd" format. A collection of dates in this format can be added to a Python list and be accessed relative to their position in the list. The first item in list has an index of zero. The next item in the list is accessed by incrementing the index by one.
Instructions
-
-
1
Launch the standard, plain-text editor application that is available on your computer.
-
2
Enter the following code into the text editor. Indent the code exactly as shown.
datelist=["2011-6-1","2011-6-12","2011-6-10","2011-6-21"]
def nextDate(current, list):
length=len(list)-1
if current >length:
print "The List is Smaller than this"
else:
if current==length:
print "Next date is: ", list[0]
else:
print "Next date is: ", list[current]
nextDate(-1,datelist)
-
-
3
Click on the "File" menu and select "Save." Save the text file with the name:
"datelist.py"
-
4
Click the "File" menu then select the appropriate option to close the text editor.
-
5
Launch the system terminal, console, or command line. At the command line prompt, type "python" then press the enter key.
-
6
At the Python command prompt, type execfile("datelist.py") and press the enter key. If your terminal opened in a directory other than the directory containing your python script, add the complete file path name for "datelist.py" to the execfile() command.
-
7
Press the "Enter" key. The interpreter should display: "Next date is: 2011-6-21."
-
8
Type "nextDate(2,datelist)" at the Python command prompt and press the "Enter" key. The interpreter should display: "Next date is: 2011-6-10."
-
1
Tips & Warnings
Code indentation matters in Python programming. Indent code with the "Tab" key or with blank spaces, but do not use both. The interpreter may run inconsistently indented code incorrectly or not at all.
References
Resources
- Photo Credit Hemera Technologies/Photos.com/Getty Images