5/17 List Comprehension Syntax Help Please!


#1

I have been working on this one for the past couple days,& I was wondering if somebody could explain what to write& why I need to write certain things? If not, can somebody just send me what they wrote& I can find out for myself? Thanks.


#2
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]

# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,11) if (x**2)%2 == 0]

print even_squares

That's what I wrote, I have forgotten what most of it means sorry I can't help anymore. If you are struggling to figure it out I know what most of it means (I think) and I can try and work out the rest.


#3

It's all part of the magic called a generator, the syntax is quite easy to remember to.

# First we must create our generator expression
def square_odds(a_list):
    return (num**2 for num in a_list if num % 2 != 0)
# As you can see I have created a function that returns a generator
# We can get the information from it in any way you would get an item from an iterator object
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(*square_odds(a))
# OUTPUT: 1 9 25 49 81

Ok, so the way a generator works is the first argument inside the generator is what is going to be worked on and returned, next is the loop that we are using to iterate over the data and finally and conditions or additional loops that you want to work on the data.

  1. First item is the item to be returned
  2. The loop to work on the data
  3. Additional loops or conditional statements to modify the data

Easy enough?

Ok, so you may be thinking what does this have to do with list comprehension.

Well if you noticed both have the same syntax, but when you surround the generator with [] or {} it then automagically turns it into a list comprehension or a dictionary comprehension depending on the data you give it.

Now take note, you can use MULTIPLE generators nested inside one another.

EXAMPLE: Single Generator

CAN BE CONVERTED TO A LIST COMPREHENSION

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 11, 12, 13, 14, 15, 16, 17, 18]
# Here is the generator, we will simply make it join the above lists
c = (item for number in (a, b) for item in number)
# Now we want to grab the info from the generator
for number in c:
    print(number)

# As list comprehension and nested generators
# This one prints them all on the same line though, you force it to print on different lines if you want
print(*[num for num in (item for number in (a, b) for item in number)])

Easy enough?

Now how about we generate a complex dictionary with a nested list which has a generator that populates it.

CODE:

# This code here generates a dict with a list of values as the value each generated
# based on the current x, y
a_map = {(x, y): [item for item in (num**(y // x) for num in range(1, 5))] for x in range(1, 5) for y in range(1, 5)}
print(a_map)

You can of course use this in way more constructive ways, You can also create your own generators and use them. It is quite simple.

In order to create a generator function you need to have a function that contains yield in the main body of the function.

Example:

def generate_square_seq(start=1):
    while True:
        yield start**2
        start += 1
        if start == 5:
            break

for _ in generate_square_seq():
    print(_)

That is about as much as I am willing to talk about right now.

Any questions?


#4

I only have 2 minutes of class left so I can't explain now, but here is my code:

doubles_by_3 = [x * 2 for x in range(1,6) if (x * 2) % 3 == 0]
even_squares = [x ** 2 for x in range(1,11) if (x ** 2) % 2 == 0]

print even_squares

Good luck :slightly_smiling:


#5

can u expalin the code please


#6

Ok for the code above @dataace98389 in the list to be generated the first condition is x ** 2 this means raising the value of x to 2 OR rather the square of x.
Next it says in range(1,11) this means in the range or between the numbers 1 and 11 excluding 11 that 11 is not counted in the range so the numbers will go from 1 to 10..
next there is if condition which says if (x ** 2) % 2 == 0 which means that if the number is squared and if on dividing it the remainder is zero then only add it to the list otherwise continue.

a slight modification can also be done in the . Here is my code given below :

even_squares = [x**2 for x in range(1,11) if x % 2 == 0]
print even_squares

in my code instead of checking whether the remainder is zero after squaring the number we check before squaring as this will help to reduce the processing time greatly for very large numbers.


#7

A post was split to a new topic: List comprehension


#8