Python: Generate And Print A List Of First And Last 5 Elements Where ...
Maybe your like
Last update on June 28 2025 12:44:47 (UTC/GMT +8 hours)
Generate Square Numbers in Range
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:
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:
For more Practice: Solve these Related Problems:
- Write a Python program to generate a list of all cube numbers within a given range.
- Write a Python program to generate a list of numbers that are both perfect squares and perfect cubes.
- Write a Python program to generate a list of numbers whose square root is an odd number.
- Write a Python program to generate a list of numbers that are squares of prime numbers.
Go to:
- Python Data Type List Exercises Home ↩
- Python Exercises Home ↩
Previous: Shuffle and print a specified list. Next: Check if each number is prime in a list of numbers.
Python Code Editor:
Tag » How To Print A List Python
-
Print Lists In Python (5 Different Ways) - GeeksforGeeks
-
How To Print A List In Python? - FavTutor
-
3 Easy Methods To Print A Python List - AskPython
-
Python List Print - 7 Different Ways To Print A List You Must Know
-
How To Print A List In Python? | Flexiple Tutorials
-
How To Print A List In Python - Codingem
-
How To "properly" Print A List? - Python - Stack Overflow
-
Python List Print - Initial Commit
-
Python List Index() - Programiz
-
Python Print List Example - HowToDoInJava
-
Create And Print Lists Using Python
-
Python Tips - How To Easily Convert A List To A String For Display
-
Python List Reverse() - Programiz
-
6 Ways To Print Lists Of List In Python