Python Tutorial · Data Structures · Lesson 14 of 42

Python Lists

Ordered, changeable collections: create, access, slice and modify lists.

Creating lists

A list stores items in order and can hold any types. It's written with square brackets.

Example 1Try it yourself
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]
print(fruits)
print(len(fruits))
print(mixed)

Output

['apple', 'banana', 'cherry']
3
[1, 'two', 3.0, True]

Accessing and slicing

Lists use the same indexing and slicing as strings:

Example 2Try it yourself
nums = [10, 20, 30, 40, 50]
print(nums[0], nums[-1])
print(nums[1:4])
print(nums[:2])
print(nums[::2])

Output

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

Changing lists

Example 3Try it yourself
fruits = ["apple", "banana"]
fruits.append("cherry")
fruits.insert(0, "kiwi")
fruits[1] = "mango"
fruits.remove("banana")
last = fruits.pop()
print(fruits, last)

Output

['kiwi', 'mango'] cherry

Copying a list

Assignment doesn't copy (both names share one list). Use .copy() or list() for a shallow copy:

Example 4Try it yourself
original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original)
print(copy)

Output

[1, 2, 3]
[1, 2, 3, 4]

Test yourself

Which method adds an item to the end of a list?

  1. add()
  2. push()
  3. append()
  4. insert()
Show answer

Answer: append()

Practice next