Python List with Examples

Learn Python lists with simple examples to create a list, access items, change values, add and remove elements, loop through lists, sort, copy, and use common list methods.

Published

Updated

Read time 8 min read

Reviewed byDeepak Prasad

Python List with Examples

A Python list is the workhorse sequence type: ordered, resizable, and mutable. This tutorial walks through syntax, indexing and slicing, adding and removing items, loops, membership, sorting, copying, and nested lists—with runnable examples you can paste into a REPL or script.

For building lists from logic in one expression, see list comprehension. For the related extend method in depth, see Python list extend and append vs extend. For an immutable sequence, see Python tuple.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is a list in Python?

A list stores zero or more references to objects in a fixed left-to-right order. You can replace, insert, or delete elements without creating a new list object. Lists are iterable, allow duplicates, and can mix types (integers, strings, other lists, and so on). The interpreter assigns each position an integer index starting at 0 for the first item.


Python list syntax

A literal list is written in square brackets with commas between items:

python
empty = []
nums = [1, 2, 3]
mixed = [1, "two", 3.0]
Output

The built-in list() constructor builds a list from any iterable (string characters, tuple elements, range values, and so on):

python
print(list("abc"))
print(list((10, 20)))
Output

That prints ['a', 'b', 'c'] then [10, 20].


How to create a list in Python

Create an empty list

Use [] or list() when you plan to fill the list later:

python
a = []
b = list()
print(a == [], len(b))
Output

Both are empty lists; the line prints True and 0.

Create a list with values

Separate items with commas inside [...]:

python
fruits = ["apple", "mango", "guava", "grapes"]
print(fruits[0], len(fruits))
Output

That prints apple and 4.

Create a list using list()

Pass any iterable to duplicate its elements into a new list:

python
digits = list(range(3))
from_tuple = list((7, 8))
print(digits, from_tuple)
Output

That prints [0, 1, 2] and [7, 8].


Access list items using index

Positive indexing

Index 0 is the first element, 1 the second, and so on:

python
nums = [10, 20, 30, 40, 50]
print(nums[0], nums[2])
Output

That prints 10 and 30.

Negative indexing

Index -1 is the last item, -2 the second last:

python
nums = [10, 20, 30, 40, 50]
print(nums[-1], nums[-2])
Output

That prints 50 and 40.

List slicing

A slice [start:stop] selects from start up to but not including stop. Omitted bounds default to the beginning or end. A step can reverse or skip elements:

python
nums = [10, 20, 30, 40, 50]
print(nums[1:4])
print(nums[:3])
print(nums[::2])
print(nums[::-1])
Output

That prints [20, 30, 40], [10, 20, 30], [10, 30, 50], then [50, 40, 30, 20, 10].


Change list items in Python

Assign to an index to replace one element:

python
colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors)
Output

That prints ['red', 'yellow', 'blue'].

You can assign to a slice to replace a whole sub-range with another iterable (possibly changing the length):

python
nums = [0, 1, 2, 3, 4]
nums[1:4] = [10, 20]
print(nums)
Output

That prints [0, 10, 20, 4].


Add items to a list

Add one item using append()

append(x) adds a single object at the end—including one list as a single nested item:

python
stack = [1, 2]
stack.append(3)
stack.append([4, 5])
print(stack)
Output

That prints [1, 2, 3, [4, 5]].

Add multiple items using extend()

extend(iterable) appends each element of the iterable one by one. Strings are iterable by character:

python
a = [1, 2]
a.extend([3, 4])
print(a)
b = [1, 2]
b.extend("ab")
print(b)
Output

That prints [1, 2, 3, 4] then [1, 2, 'a', 'b'].

Add item at a specific index using insert()

insert(i, x) inserts x before the position that currently holds index i (pushing the rest right):

python
words = ["one", "two", "four", "five"]
words.insert(2, "three")
print(words)
Output

That prints ['one', 'two', 'three', 'four', 'five'].


Remove items from a list

Remove by value using remove()

remove(value) deletes the first matching element and raises ValueError if it is missing. For more removal patterns, see remove element from list.

python
items = ["one", "two", "one", "three"]
items.remove("one")
print(items)
Output

That prints ['two', 'one', 'three']—only the first "one" is removed.

Remove by index using pop()

pop(i) removes and returns the item at index i. Called with no index, it pops the last item:

python
nums = ["one", "two", "three", "four"]
last = nums.pop()
first = nums.pop(0)
print(last, first, nums)
Output

That prints four, one, then ['two', 'three'].

Remove all items using clear()

clear() empties the list in place:

python
nums = [1, 2, 3]
nums.clear()
print(nums)
Output

That prints [].


Loop through a list in Python

Loop using for

The simplest pattern visits each element once:

python
fruits = ["apple", "mango", "guava", "grapes"]
for fruit in fruits:
    print(fruit)
Output

Each name prints on its own line in list order.

Loop using index and range()

Use range(len(items)) when you need the index—for example to change elements while walking:

python
nums = [2, 4, 6]
for i in range(len(nums)):
    nums[i] = nums[i] * 2
print(nums)
Output

That prints [4, 8, 12]. When you need both index and value, prefer enumerate(nums) over manual indexing.


Check if an item exists in a list

Use in (and not in) for membership tests:

python
fruits = ["apple", "mango", "guava"]
print("mango" in fruits)
print("banana" not in fruits)
Output

That prints True then True.

To find the first index of a value, use list.index(value) (optional start and end bounds); it raises ValueError if the value is absent.


Find length of a list

len(my_list) returns the number of elements:

python
print(len([10, 20, 30]))
print(len([]))
Output

That prints 3 then 0.


Sort and reverse a list

sort() sorts the list in place (ascending by default) and returns None. Use key= for custom ordering and reverse=True for descending. For a full sorting walkthrough, see sort a list in Python.

python
nums = [4, 3, 1, 2, 5]
nums.sort()
print(nums)

words = ["Monday", "Tuesday", "Wednesday", "Thursday"]
words.sort(key=str.lower)
print(words)
Output

That prints [1, 2, 3, 4, 5] then ['Monday', 'Thursday', 'Tuesday', 'Wednesday'] (lexicographic order with default string rules).

To obtain a new sorted list without mutating the original, use sorted(nums) instead of nums.sort().

reverse() reverses the list in place:

python
nums = [1, 2, 3, 4]
nums.reverse()
print(nums)
Output

That prints [4, 3, 2, 1].


Copy a list in Python

Assignment does not copy: two names refer to one list. copy() (or a full slice [:]) builds a shallow copy—top-level elements are shared with the original if they are mutable objects. See copy a list in Python for shallow vs deep copy patterns.

python
original = [1, 2, [3, 4]]
shallow = original.copy()
original[0] = 99
original[2][0] = 300
print(shallow)
Output

That prints [1, 2, [300, 4]]: reassignment to original[0] only rebinds the first slot on original, while the nested list at index 2 is still the same object in both lists, so the inner change shows up in shallow. For fully independent nested structures, use copy.deepcopy from the copy module.


Nested list in Python

Lists can contain other lists—common for matrices or records:

python
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[0][2])
matrix[1][0] = 40
print(matrix)
Output

That prints 3 then [[1, 2, 3], [40, 5, 6]]. Access row first, then column. For deeper nesting patterns with mappings, see nested dictionary in Python.


List methods quick reference table

Method Effect
append(x) Add one element at end
extend(iter) Append each element of iter
insert(i, x) Insert x before index i
remove(x) Remove first value equal to x
pop(i=-1) Remove and return item at index
clear() Remove all elements
index(x, start, end) First index of x in optional range
count(x) Count occurrences of x
sort(*, key=None, reverse=False) Sort in place
reverse() Reverse in place
copy() Shallow copy of the list

Common mistakes with Python lists

  • Treating sort() or reverse() as if they returned a new list—they mutate in place and return None; assign sorted(x) when you need a fresh sequence.
  • Using append([a, b]) when you meant extend([a, b]), which leaves a single nested list element.
  • Expecting b = a to duplicate data; both names alias the same list until you copy.
  • Assuming copy() fixes nested mutability; inner lists are still shared, and only in-place changes to shared objects appear in every shallow copy.
  • Changing a list while iterating over it without care; iterate over a copy of the list or build a new list if removals can skip elements.

List vs tuple vs set vs dictionary

Type Ordered Mutable Typical use
List Yes Yes Sequence you grow or edit
Tuple Yes No Fixed record, dict key
Set Treat as unordered for logic Yes Unique membership tests
Dictionary Yes (insertion order, CPython 3.7+) Yes Map keys to values; keys unique

Dictionaries map keys to values; from Python 3.7 onward, dict preserves insertion order when you iterate. Sets require hashable elements and model unordered unique collections for membership and set logic. See list vs set vs tuple vs dictionary for a side-by-side comparison.


Summary

Python lists are ordered, mutable sequences in square brackets: you create them with literals or list(), read and write with indices and slices, grow with append, extend, and insert, shrink with remove, pop, and clear, and walk them with for or index loops. Membership uses in; length uses len. Sorting and reversing usually mean sort/reverse in place or sorted/reversed when you must keep the original. Copying shares inner objects unless you deep-copy nested data. Keep the list versus tuple versus set versus dict roles in mind when you pick a collection type.


References


Frequently Asked Questions

1. What is a Python list?

An ordered, mutable sequence written with square brackets; elements are indexed from zero, can repeat, and may have different types in the same list.

2. What is the difference between append and extend?

append(x) adds a single object x as one new tail element; extend(iterable) loops iterable and appends each element separately, so extend([1,2]) adds two items while append([1,2]) adds one nested list item.

3. Does list.sort() return a new sorted list?

No. sort() rearranges the list in place and returns None; use the built-in sorted(sequence) when you need a new list and must leave the original order unchanged.

4. Does assignment copy a list?

No. b = a makes b reference the same list object; changing b affects a unless you build an independent copy with copy(), list slicing [:], or copy.deepcopy for fully independent nested structures.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …