1
My Date = 2015-07-30
          2015-07-31
          2015-08-03
          2015-08-04
          2015-08-05
          2015-08-06
          2015-08-07
          2015-08-10
          2015-08-11
          2015-08-12
          2015-08-13
          2015-08-14

How can I call every 2nd date from here? I tried this but this doesn't work.

for i in range(0, len(Date), 2):
        abc = Date[i] 
3
  • 2
    What is MyDate? A list? Furthermore what you you mean with "call"? What is the expected output? Commented Jul 18, 2017 at 14:09
  • 2
    Consider replacing your pseudo code with actual Python. Commented Jul 18, 2017 at 14:11
  • My Date is a list. The expected output is like 2015-07-31,2015-08-04,2015-08-06 etc every 2nd date. Commented Jul 18, 2017 at 14:12

2 Answers 2

6

You can write this to get every other date (index 0, 2, 4, ...) from your list:

Date[::2]

To get the other dates (index 1, 3, ...), you can write:

Date[1::2]

You can look at this answer for an explanation of the slice notation.

Since Date is a list, you might want to call it dates in order to indicate it's a collection:

dates = """2015-07-30
2015-07-31
2015-08-03
2015-08-04
2015-08-05
2015-08-06
2015-08-07
2015-08-10
2015-08-11
2015-08-12
2015-08-13
2015-08-14""".split()
print(dates[::2])
# ['2015-07-30', '2015-08-03', '2015-08-05', '2015-08-07', '2015-08-11', '2015-08-13']
print(dates[1::2])
# ['2015-07-31', '2015-08-04', '2015-08-06', '2015-08-10', '2015-08-12', '2015-08-14']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I will try this.
1
my_dates = ['2015-07-30', '2015-07-31', '2015-08-03', '2015-08-04', '2015-08-05', '2015-08-06', '2015-08-07', '2015-08-10', '2015-08-11', '2015-08-12', '2015-08-13', '2015-08-14']

Using list comprehension:

print([my_dates[i] for i in range(1, len(my_dates), 2)])

Output:

['2015-07-31', '2015-08-04', '2015-08-06', '2015-08-10', '2015-08-12', '2015-08-14']

For above sample code, you can replace start index as 1 and observe by printing:

for i in range(1, len(my_dates), 2):
    abc = my_dates[i]
    print(abc)

1 Comment

@S.A Great! I think the other answer is more easier and efficient but I just tried to fix error in the sample code .Happy Coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.