HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Lists

Lists

Creating lists, accessing elements, adding/removing, sorting, length, and iterating with a loop.

Simple enough for a 5-year-old to understand

Create and access a list

A list holds multiple values in order. It's written with square brackets; elements are accessed with an index starting at 0.

Example code
1
colors = ["red", "purple", "green"]
A list with three elements.
DataA list with three elements.
2
print(colors[0])
First element: al (counting starts at 0!).
Output / InputFirst element: al (counting starts at 0!).
3
print(colors[-1])
Last element: green (negative = from the end).
Output / InputLast element: green (negative = from the end).
DataOutput / Input
💡 Hint: The first element is items[0], not items[1]. This is the most common mistake.

Adding and length

Example code
1
basket = ["apple"]
A list with one element.
DataA list with one element.
2
basket.append("pear")
Appends "armut" to the end.
CodeAppends "armut" to the end.
3
print(basket)
['apple', 'pear']
Output / Input['apple', 'pear']
4
print(len(basket))
2 — the number of elements.
Output / Input2 — the number of elements.
DataCodeOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.What is colors[0] in the list colors = ["red", "purple"]?

About this topic

A list is a structure that holds multiple values in an ordered manner under a single name. Instead of holding the grades of a hundred students in a hundred separate variables, you store them in a single list and loop through them. It is the most commonly used data structure in programming.

Unlike strings, Python lists are MUTABLE: you can add, remove, and update an element's value in place. Also, different types can coexist in the same list — numbers, strings, and another list can all be together.

What you will learn

  • Creating a list and accessing its elements by index
  • Modifying a list with append, insert, remove, and pop
  • Getting a sublist using slicing
  • Iterating over a list with a loop
  • Sorting with sort and sorted; using len, sum, and max
  • Generating lists in a single line with list comprehension

When to use?

You use a list for any dataset where order matters and the count can change: lines read from a file, records returned from an API, items in a shopping cart, results accumulated in a loop.

If the number of elements is fixed and won't change, a tuple is more suitable; if elements need to be unique, a set is better; if access by name is required, a dictionary is more appropriate.

Common mistakes

Wrong

items = [1, 2, 3]
items = items.append(4)
print(items)

append modifies the list IN PLACE and returns None. Because you reassigned the return value, items becomes None and you get "AttributeError: 'NoneType' object has no attribute" errors in subsequent operations.

Correct

items = [1, 2, 3]
items.append(4)
print(items)

Wrong

numbers = [1, 2, 3, 4]
for n in numbers:
    if n % 2 == 0:
        numbers.remove(n)

Deleting elements from a list while iterating over it shifts the indices; the loop skips some elements and the result is wrong. You don't get an error message, it silently fails — which makes it more dangerous.

Correct

numbers = [1, 2, 3, 4]
numbers = [n for n in numbers if n % 2 != 0]

Wrong

a = [1, 2, 3]
b = a
b.append(4)
print(a)

The equals sign does not copy the list, it gives the same list a second name. Changes you make via b also show up in a. If you want a copy, you must explicitly copy it.

Correct

a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)

Frequently asked questions

What is the difference between sort and sorted?

sort sorts the list in place and returns None; sorted leaves the original list untouched and returns a new sorted list. Use sorted if you need to preserve the original order.

What is list comprehension and when is it used?

It is a way to transform or filter a list in a single line. It replaces a three-line loop and runs faster. However, when conditions get complicated, readability drops; if there are more than two conditions, a normal loop is clearer.

How do I check if an element is in a list?

With the in operator. In very large lists, this operation searches from start to finish, meaning it is slow. If you frequently check for existence, using a set instead of a list is much faster.

Summary

A list is an ordered and mutable data structure; it is managed with methods like append, remove, and sort, and iterated over with loops. The two most common traps are: in-place modifying methods returning None, and the equals sign not creating a copy.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code