Lists

Python - A Quick Start for existing Programers

4 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

A list in Python is a built-in, ordered, mutable (changeable), and iterable collection of elements.

  • Ordered: Items have a defined order and can be accessed by index (list[0]).
  • Mutable: You can add, remove, or change items after creation.
  • Heterogeneous: Can store different data types in the same list.
  • Indexed: Zero-based indexing (list[0] is the first element).
  • []: Lists are defined by using [ ] square brackets.

Examples:

# List of strings
fruits = ["apple", "banana", "cherry"]

# List of integers
nums = [3,4,5,6,10,20]

# List of mixed data types
data = [4, "Frog", 8.2]

Python lists are indexed collections, however you can also use negative indexing:

  • Zero-based indexing → the first element is at index 0, the second at 1, and so on.
  • Negative indexing → counts from the end: -1 is the last element, -2 the second-to-last, etc.

Examples:

nums = [10, 20, 30, 40, 50]

# Zero-based indexing
print("First element:", nums[0])
# 10
print("Second element:", nums[1])
# 20

# Negative indexing
print("Last element:", nums[-1])
# 50
print("Second to last:", nums[-2])
# 40

# Slicing works with both
print("First three:", nums[:3])
# [10, 20, 30]
print("Last three:", nums[-3:])
# [30, 40, 50]



Built-in functions used with lists

Python has a number of built in functions that can be used with lists:

  • len(list) → number of elements
  • min(list), max(list) → smallest/largest element
  • sum(list) → sum of elements (if numeric)
  • sorted(list) → returns a new sorted list (does not modify original)
  • enumerate(list) → get index and value pairs
  • any(list), all(list) → logical checks

Examples:

nums = [3, 1, 4, 1, 5, 9]

# len(list) → number of elements
print("Length:", len(nums))
# 6

# min(list), max(list) → smallest/largest element
print("Min:", min(nums))
# 1
print("Max:", max(nums))
# 9

# sum(list) → sum of elements
print("Sum:", sum(nums))
# 23

# sorted(list) → returns a new sorted list (original unchanged)
print("Sorted copy:", sorted(nums))
# [1, 1, 3, 4, 5, 9]
print("Original list still:", nums)

# enumerate(list) → index + value pairs
for i, val in enumerate(nums):
    print(f"Enumerate: index={i}, value={val}")

# any(list), all(list) → logical checks
print("Any > 8?", any(n > 8 for n in nums))
# True (9 is > 8)
print("All > 0?", all(n > 0 for n in nums))
# True (all positive)



Lists own functions

Lists also have their own functions that can be called by using the . notation between the variable name and the function name:

Function

Description

append(x)

Add an item x to the end of the list.

extend(iterable)

Add all elements from another iterable (like a list/tuple) to the end.

insert(i, x)

Insert item x at position i.

remove(x)

Remove the first occurrence of x. Raises ValueError if not found.

pop([i])

Remove and return the item at index i. If i is omitted, removes and returns the last item.

clear()

Remove all items (makes the list empty).

index(x, [start], [end])

Return the first index of value x. Optional start and end arguments limit the search.

count(x)

Return the number of occurrences of x.

sort(*, key=None, reverse=False)

Sort the list in ascending order (in-place). Optional key function and reverse flag.

reverse()

Reverse the list in place.

copy()

Return a shallow copy of the list.



Examples:

nums = [3, 1, 4, 1, 5]
print("Original:", nums)
# Original: [3, 1, 4, 1, 5]

# append(x) → add item to end
nums.append(9)
print("append(9):", nums)
# append(9): [3, 1, 4, 1, 5, 9]

# extend(iterable) → add elements from another iterable
nums.extend([2, 6])
print("extend([2, 6]):", nums)
# extend([2, 6]): [3, 1, 4, 1, 5, 9, 2, 6]

# insert(i, x) → insert at position
nums.insert(2, 7)
print("insert(2, 7):", nums)
# insert(2, 7): [3, 1, 7, 4, 1, 5, 9, 2, 6]

# remove(x) → remove first occurrence
nums.remove(1)
print("remove(1):", nums)
# remove(1): [3, 7, 4, 1, 5, 9, 2, 6]

# pop([i]) → remove and return item at index (default last)
last = nums.pop()
print("pop() removed:", last, "| list:", nums)
# pop() removed: 6 | list: [3, 7, 4, 1, 5, 9, 2]
third = nums.pop(2)
print("pop(2) removed:", third, "| list:", nums)
# pop(2) removed: 4 | list: [3, 7, 1, 5, 9, 2]

# clear() → remove all items
copy_for_clear = nums.copy()
copy_for_clear.clear()
print("clear():", copy_for_clear)
# clear(): []

# index(x[, start[, end]]) → find first occurrence index
print("index of 5:", nums.index(5))
# index of 5: 3

# count(x) → count occurrences
print("count of 1:", nums.count(1))
# count of 1: 1

# sort(key=None, reverse=False) → in-place sort
nums.sort()
print("sort():", nums)
# sort(): [1, 2, 3, 5, 7, 9]
nums.sort(reverse=True)
print("sort(reverse=True):", nums)
# sort(reverse=True): [9, 7, 5, 3, 2, 1]

# reverse() → reverse in-place
nums.reverse()
print("reverse():", nums)
# reverse(): [1, 2, 3, 5, 7, 9]

# copy() → shallow copy
nums_copy = nums.copy()
print("copy():", nums_copy)
# copy(): [1, 2, 3, 5, 7, 9]



Casting to a list in

You can call list(x) to create a list from any iterable (something you can loop over).

Works with:

  • Strings → breaks into characters
  • Tuples → converts into list of elements
  • Sets → unordered elements become a list
  • Dictionaries → by default, only keys are taken
  • Range objects → numbers expanded into a list
  • Other iterables (generators, iterators, files, custom classes that implement __iter__)

Does not work with non-iterables (like int, float, None) → raises TypeError.


Examples:

# String → list of characters
print(list("hello"))
# ['h', 'e', 'l', 'l', 'o']

# Tuple → list
print(list((1, 2, 3)))
# [1, 2, 3]

# Set → list (unordered)
print(list({1, 2, 3}))
# [1, 2, 3] (order may vary)

# Dictionary → keys only
print(list({"a": 1, "b": 2}))
# ['a', 'b']

# Range → expanded list of numbers
print(list(range(5)))
# [0, 1, 2, 3, 4]

# Generator → consumed into list
gen = (x**2 for x in range(5))
print(list(gen))
# [0, 1, 4, 9, 16]




List comparisons

In Python, lists are compared lexicographically (like words in a dictionary):

  • Compare the first elements of each list.
  • If they differ, that decides the result.
  • If they’re equal, move to the next pair of elements.
  • If all compared elements are equal but one list is shorter, the shorter one is considered less.

Rules for List Comparisons

  • Uses standard comparison operators: <, <=, >, >=, ==, !=.
  • Works only if the elements themselves are comparable (<, > must make sense for the element types).
  • If element types are not comparable (e.g., [1] < ["a"]), it raises a TypeError.
  • Think of list comparison like comparing words: "cat" < "dog" because "c" < "d".
  • For lists, [1, 2, 3] < [1, 2, 4] because 3 < 4.

Examples:

# Equal lists
print([1, 2, 3] == [1, 2, 3])
# True
print([1, 2, 3] == [1, 2, 4])
# False

# Less/greater based on first differing element
print([1, 2, 3] < [1, 2, 4])
# True (3 < 4 at index 2)
print([1, 3] > [1, 2, 99])
# True (3 > 2 at index 1)

# Shorter list is smaller if all compared elements are equal
print([1, 2] < [1, 2, 0])
# True
print([1, 2, 3] > [1, 2])
# True

# Mixed types (error)
try:
    print([1] < ["a"])
except TypeError as e:
    print("Error:", e)



List Comprehension

  • A concise way to create lists.
  • Equivalent to a for loop but shorter and more readable.

Syntax:

[expression for item in iterable if condition]

Benefits:

  • Cleaner & faster than loops.
  • Can include conditions (if).
  • Can nest comprehensions (though readability can suffer).

Examples:

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

# Square each number
squares = [x**2 for x in nums]
print("Squares:", squares)

# Even numbers only
evens = [x for x in nums if x % 2 == 0]
print("Evens:", evens)

# Create a list of tuples (number, square)
pairs = [(x, x**2) for x in nums]
print("Pairs:", pairs)

# ----------------------------------------
# Nested comprehensions
# ----------------------------------------
matrix = [[1, 2, 3], [4, 5, 6]]

# Flatten a 2D list
flattened = [num for row in matrix for num in row]
print("Flattened:", flattened)

# Transpose matrix
transpose = [[row[i] for row in matrix] for i in range(3)]
print("Transpose:", transpose)

# ----------------------------------------
# Using functions
# ----------------------------------------
def square(x): return x * x

# Apply function
squared = [square(x) for x in nums]
print("Squared with function:", squared)

# ----------------------------------------
# Conditional expressions inside comprehension
# ----------------------------------------
labels = ["even" if x % 2 == 0 else "odd" for x in nums]
print("Even/Odd labels:", labels)




Full demonstration of lists

# --- Creating a list ---
nums = [3, 1, 4, 1, 5]
print("Original:", nums)

# --- Indexing & Slicing ---
print("First element:", nums[0])
# 3
print("Last element:", nums[-1])
# 5
print("First 3:", nums[:3])
# [3, 1, 4]
print("Last 2:", nums[-2:])
# [1, 5]

# --- Built-in functions ---
print("Length:", len(nums))
# 5
print("Min:", min(nums))
# 1
print("Max:", max(nums))
# 5
print("Sum:", sum(nums))
# 14
print("Sorted copy:", sorted(nums))
# [1, 1, 3, 4, 5]
print("Original unchanged:", nums)

print("Enumerate:")
for i, val in enumerate(nums):
    print(f" index={i}, value={val}")

print("Any > 4?", any(n > 4 for n in nums))
# True
print("All > 0?", all(n > 0 for n in nums))
# True

# --- List Methods ---
nums.append(9)
print("append(9):", nums)

nums.extend([2, 6])
print("extend([2, 6]):", nums)

nums.insert(2, 7)
print("insert(2, 7):", nums)

nums.remove(1) # removes first 1
print("remove(1):", nums)

last = nums.pop()
print("pop() removed:", last, "| list:", nums)

second = nums.pop(2)
print("pop(2) removed:", second, "| list:", nums)

copy_for_clear = nums.copy()
copy_for_clear.clear()
print("clear():", copy_for_clear)

print("index of 5:", nums.index(5))
print("count of 1:", nums.count(1))

nums.sort()
print("sort():", nums)
nums.sort(reverse=True)
print("sort(reverse=True):", nums)

nums.reverse()
print("reverse():", nums)

nums_copy = nums.copy()
print("copy():", nums_copy)

# --- Casting to list ---
print("list('hello'):", list("hello"))
print("list((1,2,3)):", list((1, 2, 3)))
print("list({1,2,3}):", list({1, 2, 3}))
# order not guaranteed
print("list({'a':1,'b':2}):", list({"a":1,"b":2}))
# keys only
print("list(range(5)):", list(range(5)))

gen = (x**2 for x in range(5))
print("list(generator):", list(gen))

# --- List Comparisons ---
print("[1,2,3] == [1,2,3]:", [1,2,3] == [1,2,3])
# True
print("[1,2,3] < [1,2,4]:", [1,2,3] < [1,2,4])
# True (3 < 4)
print("[1,3] > [1,2,99]:", [1,3] > [1,2,99])
# True (3 > 2)
print("[1,2] < [1,2,0]:", [1,2] < [1,2,0])
# True (shorter)
print("[1,2,3] > [1,2]:", [1,2,3] > [1,2])
# True (longer)

try:
    print([1] < ["a"]) # invalid comparison
except TypeError as e:
    print("Error on mixed types:", e)
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact