﻿ Python: Generate and print a list of first and last 5 elements where the values are square of numbers between two numbers - w3resource

# Python: Generate and print a list of first and last 5 elements where the values are square of numbers between two numbers

## Python List: Exercise - 16 with Solution

Write a Python program to generate and print a list of the first and last 5 elements where the values are square numbers between 1 and 30 (both included).

Pictorial Presentation: Sample Solution:

Python Code:

``````def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l[:5])
print(l[-5:])

printValues()
```
```

Sample Output:

```[1, 4, 9, 16, 25]
[256, 289, 324, 361, 400]
```

Explanation:

In the above example -

def printValues():  -> Defines a function named printValues.

l = list()  -> Initializes an empty list named l.

```for i in range(1,21):
l.append(i**2)```

Iterates through numbers 1 to 20 using a for loop and calculates their square, then appends the result to the l list.

print(l[:5])  -> Prints the first five elements of the l list using slice notation.

print(l[-5:])  -> Prints the last five elements of the l list using slice notation.

printValues()  -> Finally calls the printValues() function. When executed, it will print the first five elements ([1, 4, 9, 16, 25]) and the last five elements ([256, 289, 324, 361, 400]) of the list of squares of numbers from 1 to 20.

Flowchart: ## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Given a predicate function, fn, and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate:

Example:

```def tips_check_prop(fn, prop):
return lambda obj: fn(obj[prop])
check_age = tips_check_prop(lambda x: x >= 25, 'age')
user = {'name': 'Owen', 'age': 25}

print(check_age(user))
```

Output:

```True
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook