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).

Visual Presentation:

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

Sample Solution:

Python Code:

# Define a function named printValues
def printValues():
    # Create an empty list 'l'
    l = list()
    # Loop from 1 to 20 (inclusive)
    for i in range(1, 21):
        # Calculate the square of 'i' and append it to the list 'l'
        l.append(i**2)
    # Print the first 5 elements of the list 'l'
    print(l[:5])
    # Print the last 5 elements of the list 'l'
    print(l[-5:])

# Call the printValues function to execute it
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:

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

Python Code Editor:

Previous: Shuffle and print a specified list.
Next: Check if each number is prime in a list of numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/list/python-data-type-list-exercise-16.php