Hackforge Academy

Category: python

Python Lists

Published on 24 Jul 2026

Explanation

A list is one of the most commonly used data structures in Python. It is an ordered, mutable collection that

Code:

fruits = ['Apple', 'Banana', 'Orange', 'Mango']

print(fruits)
print('First Fruit:', fruits[0])
print('Second Fruit:', fruits[1])
print('Last Fruit:', fruits[-1])

print('First Three Fruits:', fruits[0:3])

for fruit in fruits:
    print(fruit)

Explanation

Python provides several built-in methods to modify lists. The append() method adds an element to the end of the list.

Code:

students = ['John', 'Alice', 'David']

students.append('Peter')
print(students)

students.insert(1, 'Mary')
print(students)

students.remove('David')
print(students)

removed = students.pop()
print('Removed:', removed)
print(students)

students.pop(0)
print(students)

Explanation

Lists can be rearranged and combined using built-in methods. The sort() method arranges elements in ascending order, while reverse() reverses

Code:

numbers = [45, 12, 89, 5, 32]

numbers.sort()
print('Sorted:', numbers)

numbers.reverse()
print('Reverse:', numbers)

numbers.extend([100, 200, 300])
print('Extended:', numbers)

numbers.clear()
print('After Clear:', numbers)

Explanation

List slicing allows you to extract a portion of a list using the syntax list[start:end:step]. Python also supports common operations

Code:

marks = [75, 82, 91, 68, 82, 95]

print('First Three:', marks[:3])
print('Last Two:', marks[-2:])
print('Alternate Values:', marks[::2])

print('Length:', len(marks))
print('82 Count:', marks.count(82))
print('Index of 91:', marks.index(91))
print('95 Exists:', 95 in marks)

for mark in marks:
    print(mark)

Explanation

A nested list is a list that contains one or more lists as its elements. Nested lists are commonly used

Code:

students = [
    ['John', 85],
    ['Alice', 90],
    ['David', 78]
]

for student in students:
    print(student[0], student[1])

numbers = [1, 2, 3, 4, 5]

squares = [num * num for num in numbers]
print('Squares:', squares)

even_numbers = [num for num in numbers if num % 2 == 0]
print('Even Numbers:', even_numbers)

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community