0% found this document useful (0 votes)
4 views10 pages

Python List Functions Guide

This document serves as a beginner-friendly reference for Python list functions and methods, covering topics such as creating, inspecting, adding, removing, searching, counting, sorting, and copying lists. It includes syntax examples and practical tips for using list methods effectively. Additionally, it highlights common mistakes and provides mini practice tasks to reinforce learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Python List Functions Guide

This document serves as a beginner-friendly reference for Python list functions and methods, covering topics such as creating, inspecting, adding, removing, searching, counting, sorting, and copying lists. It includes syntax examples and practical tips for using list methods effectively. Additionally, it highlights common mistakes and provides mini practice tasks to reinforce learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python List Functions

and Methods
A practical beginner-friendly reference with runnable examples

What this guide covers Examples

Creating and inspecting lists list(), len(), membership

Adding and removing items append(), extend(), insert(), pop()

Searching and counting index(), count()

Ordering and copying sort(), sorted(), reverse(), copy()

Useful built-in functions min(), max(), sum(), enumerate(), zip()

Important: A method is called on a list, such as [Link](5). A built-in function receives the
list as an argument, such as len(numbers).

All examples use Python 3.

Python Lists - Common Methods and Functions Page 1


Quick Reference Table
Use this page when you need to remember the correct name or purpose quickly.

Method / function Purpose Changes original list?

list(iterable) Create a list No

len(lst) Number of items No

append(x) Add one item at the end Yes

extend(iterable) Add several items Yes

insert(i, x) Insert at a position Yes

remove(x) Remove first matching value Yes

pop([i]) Remove and return an item Yes

clear() Remove all items Yes

index(x) Find first matching position No

count(x) Count matching values No

sort() Sort in place Yes

sorted(lst) Return a sorted copy No

reverse() Reverse in place Yes

copy() Make a shallow copy No

min / max / sum Calculate a simple result No

Rule of thumb: Methods such as append(), remove(), and sort() modify the existing list. Functions
such as len() and sorted() return a result without modifying it.

Python Lists - Common Methods and Functions Page 2


1. Creating and Inspecting Lists
list() - Create a list
Syntax: list(iterable)
Converts another iterable, such as a string, tuple, or range, into a list.

letters = list("cat")
numbers = list(range(1, 5))

print(letters) # ['c', 'a', 't']


print(numbers) # [1, 2, 3, 4]

len() - Count items


Syntax: len(list_name)
Returns the number of items in a list.

fruits = ["apple", "banana", "mango"]


print(len(fruits)) # 3

Membership: in and not in


Syntax: value in list_name
Checks whether a value is present. The result is either True or False.

fruits = ["apple", "banana", "mango"]

print("banana" in fruits) # True


print("grape" not in fruits) # True

Indexing and slicing


Syntax: list_name[index] | list_name[start:stop:step]
Indexing gets one item. Slicing gets a new list containing a selected range.

colors = ["red", "green", "blue", "yellow"]

print(colors[0]) # red
print(colors[-1]) # yellow
print(colors[1:3]) # ['green', 'blue']
print(colors[::-1]) # reversed copy

Python Lists - Common Methods and Functions Page 3


2. Adding Items
append() - Add one item
Syntax: list_name.append(item)
Adds exactly one item to the end of the list.

tasks = ["study", "exercise"]


[Link]("sleep")

print(tasks)
# ['study', 'exercise', 'sleep']

extend() - Add multiple items


Syntax: list_name.extend(iterable)
Adds every item from another iterable to the end of the list.

numbers = [1, 2]
[Link]([3, 4, 5])

print(numbers)
# [1, 2, 3, 4, 5]

insert() - Add at a position


Syntax: list_name.insert(index, item)
Inserts an item at a specific index and shifts later items to the right.

names = ["Asha", "Chen"]


[Link](1, "Ben")

print(names)
# ['Asha', 'Ben', 'Chen']

append() vs extend(): append([3, 4]) adds one nested list, while extend([3, 4]) adds the two
numbers separately.

a = [1, 2]
[Link]([3, 4])
print(a) # [1, 2, [3, 4]]

b = [1, 2]
[Link]([3, 4])
print(b) # [1, 2, 3, 4]

Python Lists - Common Methods and Functions Page 4


3. Removing Items
remove() - Remove by value
Syntax: list_name.remove(value)
Removes the first item equal to the given value. It raises ValueError if the value is absent.

fruits = ["apple", "banana", "apple"]


[Link]("apple")

print(fruits)
# ['banana', 'apple']

pop() - Remove and return an item


Syntax: list_name.pop() | list_name.pop(index)
Without an index, removes the last item. With an index, removes that position. The removed value
is returned.

scores = [72, 85, 91]


last_score = [Link]()
first_score = [Link](0)

print(last_score) # 91
print(first_score) # 72
print(scores) # [85]

clear() - Remove everything


Syntax: list_name.clear()
Deletes all items but keeps the list object itself.

cart = ["book", "pen", "bag"]


[Link]()

print(cart) # []

del - Delete by index or slice


Syntax: del list_name[index_or_slice]
The del statement can delete one position, a range, or the whole variable.

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


del numbers[1]
print(numbers) # [10, 30, 40, 50]

del numbers[1:3]
print(numbers) # [10, 50]

Python Lists - Common Methods and Functions Page 5


4. Searching and Counting
index() - Find a position
Syntax: list_name.index(value[, start[, stop]])
Returns the index of the first matching value. It raises ValueError when no match exists.

animals = ["cat", "dog", "rabbit", "dog"]


position = [Link]("dog")

print(position) # 1

count() - Count matching values


Syntax: list_name.count(value)
Returns how many times a value occurs.

votes = ["yes", "no", "yes", "yes"]


print([Link]("yes")) # 3

Safe search pattern: Check membership before calling index() when a missing value is possible.

animals = ["cat", "dog", "rabbit"]


target = "fox"

if target in animals:
print([Link](target))
else:
print("Not found")

Python Lists - Common Methods and Functions Page 6


5. Sorting, Reversing, and Copying
sort() - Sort the original list
Syntax: list_name.sort(key=None, reverse=False)
Sorts the list in place and returns None.

numbers = [5, 2, 9, 1]
[Link]()
print(numbers) # [1, 2, 5, 9]

[Link](reverse=True)
print(numbers) # [9, 5, 2, 1]

sorted() - Return a sorted copy


Syntax: sorted(iterable, key=None, reverse=False)
Creates and returns a new sorted list without modifying the original iterable.

numbers = [5, 2, 9, 1]
ordered = sorted(numbers)

print(ordered) # [1, 2, 5, 9]
print(numbers) # [5, 2, 9, 1]

Using key= while sorting


Syntax: sorted(items, key=function)
The key function tells Python what value to use for comparison.

names = ["Alexander", "Bo", "Catherine"]


by_length = sorted(names, key=len)

print(by_length)
# ['Bo', 'Alexander', 'Catherine']

reverse() - Reverse the original order


Syntax: list_name.reverse()
Reverses the list in place. It does not sort the values.

letters = ["a", "b", "c"]


[Link]()

print(letters) # ['c', 'b', 'a']

copy() - Make a shallow copy


Syntax: new_list = old_list.copy()
Creates a separate outer list. Nested mutable objects are still shared.

original = [1, 2, 3]
duplicate = [Link]()
[Link](4)

print(original) # [1, 2, 3]
print(duplicate) # [1, 2, 3, 4]

Python Lists - Common Methods and Functions Page 7


6. Useful Built-in Functions with Lists
min() and max()
Syntax: min(list_name) | max(list_name)
Return the smallest or largest item.

temperatures = [28, 31, 26, 30]

print(min(temperatures)) # 26
print(max(temperatures)) # 31

sum()
Syntax: sum(list_name[, start])
Adds numeric items. An optional start value can be included.

prices = [120, 80, 50]

print(sum(prices)) # 250
print(sum(prices, 10)) # 260

enumerate() - Get index and value


Syntax: enumerate(iterable, start=0)
Produces pairs containing an index and its item. It is especially useful in loops.

fruits = ["apple", "banana", "mango"]

for index, fruit in enumerate(fruits, start=1):


print(index, fruit)

# 1 apple
# 2 banana
# 3 mango

zip() - Combine lists position by position


Syntax: zip(iterable1, iterable2, ...)
Pairs corresponding items. Iteration stops when the shortest iterable ends.

names = ["Asha", "Ben", "Chen"]


scores = [88, 93, 79]

for name, score in zip(names, scores):


print(name, score)

# Asha 88
# Ben 93
# Chen 79

Python Lists - Common Methods and Functions Page 8


7. Practical List Patterns
These are not list methods, but they are among the most useful ways to work with lists.

List comprehension - Transform items


Syntax: [expression for item in iterable]
Creates a new list using a compact loop-like expression.

numbers = [1, 2, 3, 4]
squares = [n ** 2 for n in numbers]

print(squares) # [1, 4, 9, 16]

Conditional list comprehension - Filter items


Syntax: [expression for item in iterable if condition]
Includes only the items that satisfy the condition.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [n for n in numbers if n % 2 == 0]

print(even_numbers) # [2, 4, 6]

Joining strings from a list


Syntax: [Link](list_of_strings)
Combines strings using a separator. join() is a string method, not a list method.

words = ["Python", "is", "fun"]


sentence = " ".join(words)

print(sentence) # Python is fun

Unpacking a list
Syntax: a, b, *rest = list_name
Assigns list items to variables. The starred variable collects remaining items.

values = [10, 20, 30, 40]


first, second, *remaining = values

print(first) # 10
print(second) # 20
print(remaining) # [30, 40]

Python Lists - Common Methods and Functions Page 9


8. Common Mistakes and Mini Practice
Mistake 1: Assigning the result of append() or sort().
numbers = [3, 1, 2]
result = [Link]()

print(result) # None
print(numbers) # [1, 2, 3]

Methods that modify a list in place usually return None. Use the list itself after calling the method.

Mistake 2: Modifying a list while iterating over it.


# Better: create a filtered list
numbers = [1, 2, 3, 4, 5]
numbers = [n for n in numbers if n % 2 != 0]

print(numbers) # [1, 3, 5]

Mistake 3: Confusing a copied list with the original.


a = [1, 2, 3]
b = a # Both names refer to the same list
[Link](4)
print(a) # [1, 2, 3, 4]

c = [Link]() # A separate outer list


[Link](5)
print(a) # [1, 2, 3, 4]
print(c) # [1, 2, 3, 4, 5]

Mini Practice
Starting list: numbers = [8, 3, 5, 3, 9]

Task Suggested method / function

Add 12 to the end append()

Count how many times 3 appears count()

Find the smallest number min()

Sort from largest to smallest sort(reverse=True)

Remove and save the last item pop()

Create a separate copy copy()

Tip: Type the examples yourself and change the values. Small experiments are one of the fastest
ways to learn Python.

Python Lists - Common Methods and Functions Page 10

You might also like