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] 
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
A.S
  • 305
  • 1
  • 4
  • 20

2 Answers2

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']
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
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)
niraj
  • 17,498
  • 4
  • 33
  • 48
  • @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.` – niraj Jul 18 '17 at 17:46