0

I am working on a bot that would work with ical files and the events inside them. The way it works is that the ical file is read in to a variable data that is then parsed by the ics library and converted in to a list of events. The variable eventlist is a <class 'list'> containing elements of the type: <class 'ics.event.Event'>

from ics import Calendar
import time
from datetime import datetime

#open the ical file for processing
with open("D:\\Downloads\\d210107c532744427a.ics", 'r') as file:
     data = file.read()
c = Calendar(data)
eventlist = list(c.events) #create a list of all the events

However, when I try to iterate over eventlist using a for loop the iterator is not an integer rather it becomes a <class 'ics.event.Event'> example below:

for x in eventlist:
    print(type(x))

Output of the above code is:

<class 'ics.event.Event'>
<class 'ics.event.Event'>
<class 'ics.event.Event'>
...

This is a problem because when trying to access an element from eventlist using eventlist[x] an error occurs since x need to be an integer.

Is there any way to suppress this behavior and make the for loop return integers for the iterator?

Edit 1: I understood that this is how for loops are supposed to behave in Python, however I would also like to know if there is a way to get the position if the current x in the list as an integer?

7
  • 2
    x is already "an element from eventlist". Just use x instead of eventlist[x]. Commented Nov 6, 2020 at 10:45
  • 1
    Does this answer your question? How does a Python for loop with iterable work? Commented Nov 6, 2020 at 10:46
  • 1
    for loops always iterate over the elements of an iterable. There is no way to "suppress" that behavior, and there is no good reason to want to. The are various built-in functions, e.g. enumerate that provide various iterators that you may find useful. Commented Nov 6, 2020 at 10:47
  • 1
    As an aside, "iterator" in Python does not mean the loop variable. An iterator is an object returned from an iterable's __iter__ method, the iterator implements a __next__ method (along with an __iter__ method itself that simply returns self) Commented Nov 6, 2020 at 10:49
  • 1
    @Coder_fox for index, event in enumerate(eventlist): ... Commented Nov 6, 2020 at 10:50

1 Answer 1

1

The loop you are using :

for x in eventlist:
    print(type(x))

defines that x is an eventlist so what you do is:

for x in eventlist:
    print(x) #to print each event 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.