Python Lists
Lists are used to store multiple items in a single variable. They are one of Python's 4 built-in
collection data types (along with Tuple, Set, and Dictionary).
• Key Properties: A list is a collection which is ordered, changeable (mutable), and
allows duplicate values.
• Syntax: Lists are created using square brackets [].
Python
# Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Core Characteristics
1. Ordered: The items have a defined order, and that order will not change (unless you use
a method to change it, like sort()). New items are added to the end.
2. Changeable: You can change, add, and remove items in a list after it has been created.
3. Allow Duplicates: Since lists are indexed, they can contain items with the same value.
Python
# Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To get the number of items in a list, use the len() function.
Python
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
# Output: 3
Data Types
List items can be of any data type, and a single list can contain a mix of different data types.
Python
# A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
The list() Constructor
You can also create a list using the list() constructor, (note the double round-brackets).
Python
thislist = list(("apple", "banana", "cherry"))
print(thislist)
Accessing Items
Access by Index
Access items by using their index number inside square brackets [].
Note: The first item has index [0].
Python
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
# Output: "banana"
Negative Indexing
Negative indexing starts from the end. -1 is the last item, -2 is the second-to-last, etc.
Python
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
# Output: "cherry"
Range of Indexes (Slicing)
Slicing lets you get a range of items, which returns a new list.
The syntax is [start:end].
• The start index is included.
• The end index is excluded.
Python
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# Return the third, fourth, and fifth item:
print(thislist[2:5])
# Output: ['cherry', 'orange', 'kiwi']
# From the beginning to index 4 (not included):
print(thislist[:4])
# Output: ['apple', 'banana', 'cherry', 'orange']
# From index 2 to the end:
print(thislist[2:])
# Output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']
# Negative range:
print(thislist[-4:-1])
# Output: ['orange', 'kiwi', 'melon']
Check if Item Exists
Use the in keyword to check if an item is present in a list.
Python
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Changing List Items
Change Item Value
Change a single item by referring to its index.
Python
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
# Output: ['apple', 'blackcurrant', 'cherry']
Change a Range of Item Values
You can change a range of items by assigning a new list to a slice.
Python
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
# Output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
Note: The length of the list will change if you insert a different number of items than you
replaced.
Python
# Replace 1 item with 2 items
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
# Output: ['apple', 'blackcurrant', 'watermelon', 'cherry']
Adding List Items
append()
To add an item to the end of the list, use the append() method.
Python
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
# Output: ['apple', 'banana', 'cherry', 'orange']
insert()
To insert an item at a specified index, use the insert() method.
Python
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)
# Output: ['apple', 'orange', 'banana', 'cherry']
extend()
To add elements from another list (or any iterable like a tuple, set, etc.) to the end of the current
list, use the extend() method.
Python
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
# Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
Removing List Items
remove()
The remove() method removes the specified item by value.
• Note: It only removes the first occurrence of the item.
Python
thislist = ["apple", "banana", "cherry", "banana"]
[Link]("banana")
print(thislist)
# Output: ['apple', 'cherry', 'banana']
pop()
The pop() method removes an item at the specified index.
• Note: If you do not specify an index, pop() removes the last item.
Python
# Remove the second item (index 1)
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
# Output: ['apple', 'cherry']
# Remove the last item
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
# Output: ['apple', 'banana']
del
The del keyword also removes an item at the specified index.
Python
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
# Output: ['banana', 'cherry']
The del keyword can also delete the list completely.
Python
del thislist
# print(thislist) # This will raise an error
clear()
The clear() method empties the list. The list still exists, but it has no content.
Python
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
# Output: []
Looping Through Lists
for Loop
Loop through the items directly.
Python
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
for Loop with range()
Loop through the items by referring to their index.
Python
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
while Loop
You can also loop using a while loop and an index.
Python
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
List Comprehension
List comprehension offers a very short, one-line syntax for creating a new list based on an
existing list.
Syntax: newlist = [expression for item in iterable if condition]
Example:
Without list comprehension:
Python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
[Link](x)
print(newlist)
# Output: ['apple', 'banana', 'mango']
With list comprehension (all in one line):
Python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
# Output: ['apple', 'banana', 'mango']
Example with an Expression:
You can manipulate the item before it's added to the new list.
Python
# Set all items to uppercase
newlist = [[Link]() for x in fruits]
print(newlist)
# Output: ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
Sorting Lists
sort() (In-Place Sort)
The sort() method sorts the original list in-place (it modifies the list). By default, it's
alphanumerical, ascending.
Python
# Sort alphabetically
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)
# Sort numerically
thislist = [100, 50, 65, 82, 23]
[Link]()
print(thislist)
• Sort Descending: Use the reverse = True argument.
Python
[Link](reverse = True)
• Case-Insensitive Sort: Use key = [Link].
Python
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link](key = [Link])
print(thislist)
# Output: ['banana', 'cherry', 'Kiwi', 'Orange']
reverse() (In-Place Reverse)
The reverse() method simply reverses the current order of the elements in-place.
Python
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link]()
print(thislist)
# Output: ['cherry', 'Kiwi', 'Orange', 'banana']
Copying Lists
Important: You cannot copy a list by simple assignment: list2 = list1.
• This only creates a reference. list2 will just be another name for list1.
• Any changes made to list1 will automatically also be made in list2 (and vice-versa).
Correct Ways to Make a Copy:
1. copy() method:
Python
thislist = ["apple", "banana", "cherry"]
mylist = [Link]()
2. list() constructor:
Python
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
3. Slicing [:]:
Python
thislist = ["apple", "banana", "cherry"]
mylist = thislist[:]
Joining Lists
There are several ways to join two or more lists:
1. Using the + operator: This creates a new list.
Python
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
# Output: ['a', 'b', 'c', 1, 2, 3]
2. Using the extend() method: This adds the items from one list to the end of the existing
list (in-place).
Python
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
[Link](list2)
print(list1)
# Output: ['a', 'b', 'c', 1, 2, 3]
List Methods Reference
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable) to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list (in-place)
sort() Sorts the list (in-place)