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.
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:
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
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:
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?
add()push()append()insert()
Show answer
Answer: append()
Practice next
- Two Sum · coding problem
- Contains Duplicate · coding problem