Metronome
Python

Python

Python - Lists

Lists in Python are one of the most versatile and frequently used data structures. They allow you to store an ordered collection of items, which can be of any type: numbers, strings, other lists, or even objects. In this section, we’ll explore what lists are, how they work under the hood, how to use them at a basic level, and provide examples with explanations.

What is a list in Python?

A list is a mutable sequence of elements that preserves the order in which they were added. This means you can add, remove, or change the elements of a list after it has been created. Lists are represented by square brackets [], with elements separated by commas.

Key characteristics of lists:

  • Ordered: Elements are stored in the order they were added.
  • Mutable: You can change the contents of a list.
  • Type Flexibility: Elements can be of different data types (e.g., numbers and strings in the same list).
  • Indexing: Each element has an index, starting from 0.
  • Lists allow duplicates, meaning identical values can appear multiple times.

📌 Example:

Here, we create a list my_list containing an integer (1), a string ("hello"), a float (3.14), and a boolean (True). When printed, it displays: [1, 'hello', 3.14, True].

Why Use Lists?

Lists are useful when you need to:

  • Store a collection of data in a specific order.
  • Quickly modify a collection (add or remove elements).
  • Work with data of mixed types.

For example, lists are often used to store computation results, to-do lists, data from files, or user input.

How are lists structured internally?

Internally, Python implements lists as dynamic arrays.

  1. Memory Allocation. Python allocates extra memory beyond the current number of elements to speed up adding new ones. When space runs out, Python automatically increases the array size (typically by 1.5 to 2 times).

  2. References to Objects. Lists don’t store data directly but hold references (pointers) to objects in memory. This allows them to contain elements of different types, as Python simply tracks where each element is located.

  3. Indexing. Each element has its own number (index),enabling fast access.

This structure makes lists highly efficient for operations like appending to the end or accessing elements by index, but less efficient for tasks like inserting at the beginning, which requires shifting all elements.

Creating lists

You can create lists in several ways:

  1. Direct assignment: Using square brackets.
  2. Empty list: [] or list().
  3. From other data: for example, you can convert a string to a list or a tuple to a list.

📌 Example:

In the first case, we define a list with three string elements right away. In the second case, we create an empty list. In the third case, we use the list() function to convert the string "abc" into a list of characters.

Creating a List with Repeated Elements

You can create a list with repeated (identical) elements using the multiplication operator.

In Python, the multiplication operator can repeat a list’s contents a specified number of times. This is handy for quickly initializing a list.

Keep in mind that when using this method with mutable objects (like nested lists), all elements will reference the same object in memory, which can lead to unexpected behavior when modified.

Creating a list from a string

The split() method in Python is a simple, convenient way to convert a string into a list by dividing it into parts based on a specified delimiter. This is particularly useful for text processing, such as handling files or strings containing words, numbers, or other elements.

The split() method is called on a string and returns a list of substrings. By default, it splits the string on whitespace characters (spaces, tabs, newlines), but you can specify any other delimiter.

✳️ Syntax:

string.split(separator=None, maxsplit=-1)

Here:

  • separator: The character or string to split by. If omitted, it defaults to splitting on whitespace characters.
  • maxsplit: Maximum number of splits. If omitted or set to -1, there’s no limit.

📌 Example:

👣 Explanation:

  • The string text is split into words based on spaces.
  • Punctuation marks remain part of the words, as split() does not remove them.

You can specify any character or substring as a separator by passing it to split().

📌 Example: Splitting by comma

📌 Example: Splitting by period

Here, the delimiter is a period (.), and the string is transformed into a list of IP address components.

When dealing with extra spaces, split() automatically ignores them.

For an empty string, the result depends on the delimiter: it returns either a list with one empty string or an empty list.

The maxsplit parameter allows you to specify how many times the string should be split. The remainder of the string remains as one element.

📌 Example:

👣 Explanation:

  • maxsplit=2 means only 2 splits are performed.
  • The first two spaces are used for splitting, and the rest of the string remains one element.

Handling Multiple Delimiters

If a string has multiple different delimiters, split() can’t handle it directly—you’ll need to use the re module (regular expressions) or preprocess the string by replacing delimiters.

📌 Example using replacement:

👣 Explanation:

  • The replace() method replaces all delimiters (;, :) with a comma (,).
  • Then split(",") splits the string by commas.

Converting to Numbers

After split(), elements remain strings. To convert strings to numbers, use map() or a list comprehension.

The split() method is a powerful, flexible tool for creating lists from strings, while remaining easy to use.

List Length

To determine how many elements a list contains, use the len() function.

📌 Example:

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

How to check a list’s type

The type() function is used to determine the data type of a variable.

This code outputs <class 'list'>, confirming that mylist is indeed a list object.

Comparison of lists

In Python, lists can be compared using comparison operators: ==, !=, <, >, <=, >=.

  • == and !=: Check if the contents (values and order) of two lists are equal or unequal.
  • <, >, <=, >=: Perform lexicographical comparisons, comparing elements one by one, like words in a dictionary.

Comparison happens element by element, from left to right, until a difference is found or one list ends.

📌 Example:

The comparison stops at the third element (3 ≠ 4), so the result is True.

How element-wise comparison works:

  • It starts with the first elements of both lists.
  • If they’re equal, it moves to the next elements (second, third, etc.).
  • If one list is shorter but matches up to its end, the shorter list is considered "less than" the longer one.
  • If the lists contain incomparable elements (e.g., numbers and strings), a TypeError occurs.
  • If elements differ, the list with the smaller element is considered "less," and comparison stops.

📌 Example:

👣 Explanation:

In the first case, the comparison reaches the third element: 3 < 4, so list1 < list2.

In the second case, list3 is shorter but matches list1 up to its end; the longer list is considered "greater."

Using sets for comparison

If order doesn’t matter, you can convert lists to sets for comparison.

📌 Example:

Sets disregard order and duplicates, so set1 and set2 are equal since they contain the same elements.

Checking for the presence of elements

Sometimes you need to check if elements from one list exist in another.

For this, it is convenient to use the in operator or convert lists to sets using set.

📌 Example:

👣 Explanation:

  • The in operator checks if a single element is present in a list.

  • The all() function with a generator checks if all elements of list2 are in list1.

Solution with converting a list to a set:

Maximum and Minimum Elements in a List

In Python, the built-in max() and min() functions find the largest and smallest values in a list, respectively. When it comes to lists, these functions can be applied to find the largest or smallest element in the list.

Both functions work with any comparable data types (e.g., numbers or strings).

If the list is empty, they will raise a ValueError exception.

📌 Example 1: Working with numbers

Strings are compared lexicographically (in alphabetical order):

📌 Example 2: Working with Strings

These functions use the < operator for comparisons.

Thus, all elements must be comparable and of the same type, or a TypeError occurs.

📌 Example 3: Mixed Types

For an empty list, you can provide a default value using the default parameter:

📌 Example 4: Empty List

Using a Key Function

You can use the key parameter to customize the comparison rule:

📌 Example 5

Here, comparison is based on string length, not lexicographical order.

Multiple lists as arguments

When you pass multiple lists as separate arguments to max() or min(), Python compares the lists themselves, not their individual elements. The comparison of lists in Python occurs element by element, from left to right, similar to lexicographical order (just like string comparison).

In this case, the function returns one of the input lists unchanged.

Read about how lists are compared in the section "Comparison of Lists."

📌 Example 6

The first elements are equal (11), so it compares the second elements (8 vs. 7). Since 7 < 8, the second list is returned as the minimum.

📌 Example 7: Passing multiple lists

  • max() returns [1, 2, 4] because, when comparing [1, 2, 3] and [1, 2, 4], the third element 4 > 3, and [1, 1, 5] is less due to its second element (1 < 2).
  • min() returns [1, 1, 5], the "smallest" list by element-wise comparison.

You can use key to change the comparison logic:

📌 Example 8: Using the key parameter

Here, comparison is based on list length, not contents.

To find the maximum or minimum element across all elements of multiple lists, combine them first (e.g., using *, +, or itertools.chain):

📌 Example 9: Combining Lists

Or alternatively:

Thus, to find the max/min across all elements, combine the lists beforehand.

For more details, refer to the section dedicated to merging lists.

Finding the maximum element is a specific case of retrieving the top-N elements from a list; see the "Sorting Lists" section for more details.

Sum of List Elements

The sum() function is a built-in Python function that calculates the sum of elements in an iterable.

✳️ Syntax:

sum(iterable, start=0)

Here:

  • iterable: A sequence (list, tuple) whose elements will be summed.
  • start: The initial value to add to the sum (defaults to 0).

Features and limitations

  • It works only with numeric values.
  • For complex calculations with high precision, the fsum() function from the math module can be used

Converting a list to a string

Sometimes you need to convert a list into a string, for example, to display data conveniently or write it to a file.

Method 1. Using str() for quick conversion

If you need a simple string representation, you can use the built-in function str():

Method 2. The .join() method

The .join() method combines all list elements into a single string with a specified separator.

📌 Example:

👣 Key points:

  • The .join() method is called on the separator string and takes the list as an argument.
  • All elements of the list must be strings. If there are numbers or other types in the list, they must first be converted to strings using str().
  • In the first case, we use a space " " as a separator to connect words into a sentence.
  • In the second case, numbers are converted to strings using a generator and then joined with a comma and a space ", ".
  • In the third case, an empty string "" as a separator combines elements without gaps.

If the list contains non-string elements without prior conversion, Python raises a TypeError.

Method 3. The pprint module

For a cleaner, more readable display of complex lists (especially nested ones), the pprint (Pretty Print) module formats data with proper indentation and line breaks.

Its pprint() function formats complex data structures with indentation and line breaks.

📌 Example:

from pprint import pprint

# Typical output of a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list)  # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Using pprint
pprint(nested_list, width=20)
# Outputs:
# [[1, 2, 3],
#  [4, 5, 6],
#  [7, 8, 9]]

You can also configure the pprint settings, such as the line width or the level of nesting.

The width parameter limits line length, affecting formatting.

Note: pprint() doesn’t produce a string for further processing—it’s for display only. Use pformat() if you need a string result.

How to Check if a List is Empty

Sometimes you need to know whether a list contains elements or if it is empty.

Method 1. Using a Conditional Statement

An empty list in Python is considered "falsy" (False) in a boolean context, while a non-empty list is "truthy" (True).

Python treats an empty list [] as False and a non-empty one as True, making this approach concise.

Method 2. Using len()

Comparing the list’s length to zero explicitly shows whether it’s empty.

Method 3. Explicit Comparison with []

This works because Python compares list contents.

It’s useful for making code very explicit, especially for beginners unfamiliar with the falsy/truthy behavior of empty lists.

In practice, the first method is preferred for its simplicity and readability.

Counting elements using the count() method

The count() method counts how many times a specific element appears in a list. It’s handy for finding the frequency of a value without writing loops.

list.count(value) returns an integer showing how many times value appears in the list.

📌 Example:

If the element isn’t in the list, count() returns 0.

Conclusion

Lists in Python are a powerful, flexible tool. They’re easy to create and use, yet have a sophisticated internal structure that ensures efficiency.

Frequently Asked Questions about Lists in Python

What is a list in Python?

A list is an ordered mutable collection of elements that can contain data of different types (numbers, strings, other lists, etc.). It is created using square brackets, for example: my_list = [1, "two", 3].

How does a list differ from a string?

A list is mutable (its elements can be modified), whereas a string is immutable (its characters cannot be changed directly). For example, my_list[0] = 5 works for a list, but my_string[0] = "a" raises an error for a string.

Why are lists called dynamic arrays?

Internally, lists in Python are implemented as dynamic arrays, meaning they resize automatically when elements are added. This makes them convenient, though operations like inserting at the beginning can be slow due to element shifting.

Can a tuple be an element of a list?

Yes, a tuple can be an element of a list, just like other types such as lists, dictionaries, sets, etc.

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.