PythonListsCore List Operations

Core List Operations

Once you’ve created a list, Python offers a rich set of operations to access, modify, and inspect its contents. Understanding these operations is key to using lists effectively.

1. Accessing Elements: Indexing and Slicing

Accessing elements is a fundamental list operation. Python’s syntax is both powerful and flexible.

Indexing: Accessing a Single Element

You can retrieve any element from a list using its zero-based index in square brackets [].

  • Positive Indexing: Starts from 0 for the first element.
  • Negative Indexing: Starts from -1 for the last element, -2 for the second-to-last, and so on. This is incredibly useful for accessing items at the end of a list without needing to know its length.

Pyground

From a list of tasks, retrieve the second task using a positive index and the last task using a negative index.

Expected Output:

The second task is: 'Write tests'
The last task is: 'Update docs'

Output:

️🚨

Accessing an index that doesn’t exist will raise an IndexError. For example, todos[4] would fail for the list above.

Slicing: Extracting a Sub-List

Slicing lets you create a new list containing a portion of the original. The syntax is list[start:stop:step].

  • start: The index to begin the slice (inclusive, defaults to 0).
  • stop: The index to end the slice (exclusive, defaults to the end of the list).
  • step: The amount to jump between elements (defaults to 1).

Extract a sub-list from the middle.

Pyground

Get the middle three numbers from a list of digits.

Expected Output:

[3, 4, 5]

Output:

A common use for slicing is to create a shallow copy of a list: new_list = original_list[:].

2. Combining and Repeating Lists

You can easily combine or duplicate lists using standard operators.

Concatenation (+) vs. Extension (.extend())

The + operator combines two lists to create a new third list, leaving the original lists unchanged.

Pyground

Combine two lists of numbers into a single new list.

Expected Output:

New list: [1, 2, 3, 4, 5, 6]\nOriginal first_half is unchanged: [1, 2, 3]

Output:

Repetition (*)

The * operator creates a new list by repeating its elements a specified number of times.

Pyground

Create a simple 'loading' animation bar of size 5.

Expected Output:

['-', '-', '-', '-', '-']

Output:

☠️

Warning: Shared References When using * on a list containing mutable objects (like other lists), it copies references, not the objects themselves. Modifying one nested element will affect all its “copies”.

# Incorrect way to create a 2D grid
bad_grid = [[0]] * 3
bad_grid[0][0] = 99
print(bad_grid) # Output: [[99], [99], [99]] -- Unexpected!
 
# Use a list comprehension for this instead
good_grid = [[0] for _ in range(3)]
good_grid[0][0] = 99
print(good_grid) # Output: [[99], [0], [0]] -- Correct!

3. Membership Testing (in)

Use the in and not in keywords to check if an item exists within a list. This is highly readable and efficient.

Pyground

Check if 'Python' is in a list of required skills.

Expected Output:

Is Python a required skill? True\nIs Java a required skill? False

Output:

4. Essential Built-in Functions

Python provides several built-in functions that are very useful for working with lists.

The len() function returns the number of items in a list.

Pyground

Find out how many items are in your shopping list.

Expected Output:

There are 4 items on the shopping list.

Output: