Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. lists-tuples-sets
9 min read

Lists, Tuples & Sets

Lists

A list is a collection of data, objects, and containers. In other languages, it is often called an array. The list is arguably the most versatile data type in Python. Objects inside a list are accessible via its index, which starts at 0.

Info
Because of Python's dynamic typing, lists can contain several data types inside the same list. Here's an example:
python
lst = [1, "string", False]

CRUD Operations

CRUD (Create, Read, Update, Delete) are the four basic operations for item storage.

Creating a list requires using square brackets and itemizing the items inside the list. Alternatively, the list() default constructor can be used. Here are a few examples of a few lists being created:

python
1lst1 = list()                  # list with 0 elements
2lst2 = []                      # list with 0 elements
3lst3 = [1,

We have a few methods for removing items from a list: clear(), remove(), and pop().

  • clear(): Removes all items from the list.
  • remove(x): Remove the first item of the list with value x
  • pop(i): Remove the value at index i

Here are some examples of removing values from a list:

python
1lst = [1, 2, 3, 4, 5, 1, 2, 3, 4,

There are several different ways to update a list. We can update values using array indexing, and the insert() and append() methods.

  • Indexing: The only method of changing a value in the list.
  • insert(i, x): Inserts value x at index i, pushing back later values as necessary.
  • append(x): Adds value x to the end of the list.

Let's add some values to the list.

python
1lst = [1, 2, 3]
2lst.insert(1, 4)     # lst = [1, 4, 2, 3]
3
Out-of-Bounds Caveats

There are two caveats to understand when handling indexing out of bounds.

  • insert(): An index past the end functions the same as append(), and an index before the start inserts at the front. As a reminder, negative indexes walk the list backward from the end.
  • lst[i]: Reading or assigning an index out of bounds raises an IndexError.

List Slicing

List slicing is a powerful tool for getting sublists from a list. The format of a list-slicing operation is:

python
sliced_lst = lst[start:stop:step]
  • start: The first index of the list. The default is the start of the list, i.e. 0.
  • stop: Where to stop slicing. This value is exclusive. The default is the end of the list, i.e. len(lst).
  • step: The incrementation number. The default is 1.
Default Arguments
Note that all these items are default. This means we can easily slice items from the beginning and end of the list.

All slicing operations are non-mutating, meaning they do not change the original list. The sliced list is returned.

Let's look at some examples of slicing a list.

python
1lst = [1, 2, 3, 4, 5]
2
3lst[1:

List Comprehension

List comprehension is a powerful method of generating and operating on lists. The most general form of a list comprehension statement is:

python
lst = [operation for item in iterable if condition]

For example, we want to list the odd numbers below 10. We can do that extremely quickly using list comprehension:

python
odds = [i for i in range(10) if i & 1]

Let's break this down, starting from the iterable:

  • Iterable: range(10). This produces the integers 0 through 9. You can see this via:
python
1>>> list(range(10))
2[0, 1, 2, 3, 4, 
  • Item: This is simply the name of the parameter we're using. This is arbitrary and can be whatever we want.
  • Return Operation: In this case, we want the number. Therefore, i suffices as our "function".
  • Condition: i & 1. This checks the lowest bit, which is set only for odd numbers. It is equivalent to i % 2 == 1.

This list comprehension is equivalent to the following loop:

python
1lst = list()
2for i in range(10):
3    if i & 1:

We can also use list comprehension to modify an existing list.

python
1lst = ["1", "2", "3", "4", "5"]
2lst = [int(i) for
  • Iterable: The list we want to modify.
  • Return Operation: Convert each item to an integer.
  • Condition: None is listed, so it yields a return for all items in iterable.

Tuples

Tuples are another data structure that, like a list, contains a collection of data. However, once they are allocated, they cannot change size, making tuples immutable objects. Tuples use parentheses () rather than square brackets [].

Success
Although immutable, tuples can contain mutable objects.

CRUD Operations

Creating a tuple is identical to creating a list, except using parentheses instead of square brackets.

python
1empty1 = tuple()                   # tuple of size 0
2empty2 = ()                        # tuple of size 0
3coord1 = (1

Reading values from a tuple is as easy as using square brackets to get items by their index. They also support slicing operations. If the index is out of range, it raises an IndexError.

python
1path1[0]         # Return: [1, 2, 3]
2empty1[0]        # IndexError: tuple index out of range
3coord2[1:3]      # Return: (3, 0)

Because tuples are immutable, you cannot assign a new item to any position. However, a mutable object stored inside a tuple can still be changed in place.

python
1coord = (1, 2)
2path = ([1, 2, 3], [1

Items inside tuples cannot be deleted. The only way to delete an item is to make another tuple with the other values and then replace the object.

Unpacking a Tuple

Since tuples are static-sized lists, we can unpack them and split their values into variables. This is useful for iterating across a list of tuples, saving time from repeated indexing, etc.

python
1coord = (1, 2)
2x, y = coord    # x = 1, y = 2

If one of the values is not needed, we can use the throwaway underscore (_) to ignore it:

python
x, _ = coord    # x = 1, y is ignored

Here is an example of how tuples get unpacked in everyday functions:

python
1names = ["John", "Barry", "Mike", "Jose"]
2
3for idx, name in enumerate(

In this case, enumerate produces a (index, item) tuple for each item in the iterable, and the for loop unpacks each one into idx and name.

Sets

Sets are unordered lists that contain no duplicate elements. They are written using curly braces ({}) and support several unique operations like union, intersect, and difference.

Syntax Conflict
Although sets are identified using curly braces ({}), these are also used for Dictionaries. An empty set must be instantiated using default constructor set(). Curly braces can only be used when instantiating sets with values.

CRUD Operations

As stated in the above warning, creating a set can only be created using the set default constructor set() or values inside curly braces.

python
1empty = set()                          # empty = set()
2set1 = {2, 3, "string", False}         # set1 = {False, 2, 3, 'string'}, in no guaranteed order

Sets are unordered, meaning they cannot be subscripted using square brackets. No items have indices. However, they can be iterated:

python
1for item in set1:
2    print(item)

Items cannot be updated; however, they can be replaced. To replace an item, you remove the old value and add the new one. We can add values to a set individually using add or from another set using update.

python
1empty = set()
2full = {2, 3, "string", False}
3

There are a few methods for removing items in a set: discard, pop, and remove.

  • discard: Remove an element from a set if it's a member, and do nothing if it's not.
  • pop: Remove and return an arbitrary element from a set, raise KeyError if the set is empty. Which element you get is an implementation detail, so don't rely on it.
  • remove: Remove an element from a set, raise KeyError if not a member.
python
1full = {2, 3, "string", False}
2
3full.discard(1)

Special Set Operations

The special set operations are ones seen when covering sets in discrete mathematics: union, intersection, and difference.

  • union: Returns a set containing all elements from both sets.
  • intersection: Returns a set containing elements contained in both sets.
  • difference: Returns elements contained in the first set but not the second.

Each also has an operator form: a | b, a & b, and a - b.

python
1>>> primes = {2, 3, 5, 7, 11}
2>>> odds = 
Success
Set comprehension is also supported and works the same as list comprehension.
2
,
3
]
# list with 3 elements
4lst4 = [1, "string", False] # list with 3 elements of different types
5
]
2lst.pop(0) # lst = [2, 3, 4, 5, 1, 2, 3, 4, 5]
3lst.remove(5) # lst = [2, 3, 4, 1, 2, 3, 4, 5]
4lst.clear() # lst = []
lst
.
append
(
5
)
# lst = [1, 4, 2, 3, 5]
4lst[0] = 0 # lst = [0, 4, 2, 3, 5]
3
]
# Return: [2, 3]
4lst[:2] # Return: [1, 2]
5lst[2:] # Return: [3, 4, 5]
6lst[:-1] # Return: [1, 2, 3, 4]
7lst[1:4:2] # Return: [2, 4]
8lst[::-1] # Return: [5, 4, 3, 2, 1]
5
,
6
,
7
,
8
,
9
]
4
lst
.
append
(
i
)
i
in
lst
]
# lst = [1, 2, 3, 4, 5]
,
2
)
# tuple of size 2
4coord2 = (2, 3, 0) # tuple of size 3
5path1 = ([1, 2, 3], [4, 5, 6]) # tuple of size 2
6path2 = (3, [1, 2, 3]) # tuple of size 2
,
2
,
3
]
)
3
4coord[0] = 3 # TypeError: 'tuple' object does not support item assignment
5path[0].append(4) # path: ([1, 2, 3, 4], [1, 2, 3])
names
)
:
4 print(idx, name)
3set2 = set([2, 3, "string", False]) # set2 = {False, 2, 3, 'string'}
4set3 = set([2, 2, "string", False]) # set3 = {False, 2, 'string'}
4
empty
.
add
(
1
)
# empty = {1}
5empty.add(4) # empty = {1, 4}
6empty.add(2) # empty = {1, 2, 4}
7empty.update(full) # empty = {False, 1, 2, 3, 4, "string"}
# full = {2, 3, "string", False}
4full.discard(False) # full = {2, 3, "string"}
5full.pop() # removes one of them, say 3: full = {2, "string"}
6full.remove(1) # KeyError: 1
7full.remove(2) # full = {"string"}
{
1
,
3
,
5
,
7
,
9
}
3>>> evens = {2, 4, 6, 8, 10}
4
5>>> evens.union(odds)
6{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
7>>> odds.intersection(primes)
8{3, 5, 7}
9>>> evens.difference(primes)
10{4, 6, 8, 10}