Hence, Using generators in place of a list can be more efficient if we just have to access the elements from the newly created list. On the other hand, a generator uses a minimal amount of memory that is almost similar to the memory required by a function. When we create a new list from an existing list, the program uses memory for storing the elements of the existing list.Let us understand both of them one by one. Generators can be used in place of a list for two reasons. Print("Elements obtained from the generator are:")Įlements obtained from the generator are: Mygen = (element ** 2 for element in myList) Here, we have used the implemented the same example given in the previous section. You can create a generator from a list using the generator comprehension as follows. The syntax for set comprehension is: generator= ( expression for element in iterable if condition ) Instead of using a generator function, we can use generator comprehension to create a generator from a list.The syntax for generator comprehension is almost identical to list comprehension. Print("Elements obtained from the square generator are:")Įlements obtained from the square generator are:Ĭonvert a list to generator using generator comprehension We can perform this operation as follows. Inside the function, we will use a for loop in which the yield statement will be used to give the squares of the elements of the existing list as output. To create a generator from a list using the generator function, we will define a generator function that takes a list as input. We can also create a generator instead of a new list to obtain squares of the elements of the existing list using generator function. Output: The given list is: Įlements obtained from the square function are: Print("Elements obtained from the square function are:")
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |