{ "cells": [ { "cell_type": "markdown", "id": "73de30fb", "metadata": {}, "source": [ "# Lists\n", "\n", "Lists are one of the most valuable and frequently used data types in Python, found at the heart of countless Python programs. So, what exactly is a list, and why are they so indispensable?\n", "\n", "In essence, a list is a dynamic and mutable collection of values. Think of it as a versatile bag that can store a variety of items—numbers, words, and even a medley of data types—all within a single container. This flexibility makes lists an invaluable asset for any Python programmer.\n", "\n", "Let's explore the concept further with a real-world analogy. Imagine you have a collection of names, distances, and mixed data types like this:" ] }, { "cell_type": "code", "execution_count": 16, "id": "5b85001f", "metadata": {}, "outputs": [], "source": [ "users = [\"Jim\", \"Dwight\", \"Michael\"]\n", "distance_in_kms = [32, 97, 51, 403, 21, 53, 81]\n", "mixed_types = [\"Jim\", 23, 3.14, True, \"Berzerk\"]" ] }, { "cell_type": "markdown", "id": "f7c5be60-e15c-4c5e-8fa1-81c69bfbf53b", "metadata": {}, "source": [ "In this example, `users` contains a list of names as strings, `distance_in_kms` stores a list of distances in `ints`, and `mixed_types` is a list that seemingly defies convention by accommodating a diverse set of data types. Lists are incredibly powerful because they allow you to organize and manipulate such data effortlessly." ] }, { "cell_type": "markdown", "id": "c293720f-707d-4595-ace4-07015d56551a", "metadata": {}, "source": [ "## Accessing List Items\n", "\n", "List items can be accessed via their index system, like this:" ] }, { "cell_type": "code", "execution_count": 17, "id": "59ea0268-a50e-479b-912b-df750933ac62", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your favourite moment when Jim pulls a prank on Dwight?\n" ] } ], "source": [ "users = [\"Jim\", \"Dwight\", \"Michael\"]\n", "print(f\"What is your favourite moment when {users[0]} pulls a prank on {users[1]}?\")" ] }, { "cell_type": "markdown", "id": "e24885b4-e7e4-4a1f-be04-94c924a8ba78", "metadata": {}, "source": [ "Or can even be accessed through negative indexing, like this:" ] }, { "cell_type": "code", "execution_count": 18, "id": "9454da2e-f431-4dce-8eb8-871f36030afe", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What was one thing that Michael did you found extra funny?\n" ] } ], "source": [ "users = [\"Jim\", \"Dwight\", \"Michael\"]\n", "print(f\"What was one thing that {users[-1]} did you found extra funny?\")" ] }, { "cell_type": "markdown", "id": "6c34ebe3-aab6-43a8-9791-845020082599", "metadata": {}, "source": [ "For more information about accessing list items, see [Slicing](./slicing.ipynb)." ] }, { "cell_type": "markdown", "id": "7829a6c3-4bb2-4663-85c1-4a216b8e0514", "metadata": {}, "source": [ "## Adding and Removing Items from Lists\n", "\n", "What makes lists truly exceptional is their mutability. Unlike some data types in Python, lists can change and adapt as your program runs. You can add, remove, or modify elements within a list, making it a dynamic tool for handling evolving data. This adaptability is particularly useful in scenarios where you need to manage collections of data that may grow or shrink in size." ] }, { "cell_type": "code", "execution_count": 19, "id": "1c5583d3-1ca2-4996-a495-88dc4888cebf", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "We've added Pam to the list!\n" ] } ], "source": [ "users = [\"Jim\", \"Dwight\", \"Michael\"]\n", "users.append(\"Pam\")\n", "print(f\"We've added {users[-1]} to the list!\")" ] }, { "cell_type": "markdown", "id": "3cc73005", "metadata": {}, "source": [ "## List Comprehensions\n", "\n", "A slightly more advanced topic, Python list comprehensions are a concise and efficient way to create lists in Python. They allow you to generate a new list by applying an expression to each item in an existing iterable (e.g., a list, tuple, or range) and optionally applying a filter condition to include only certain items. List comprehensions are a more compact alternative to using traditional for loops to build lists.\n", "\n", "The basic syntax of a list comprehension is as follows:" ] }, { "cell_type": "code", "execution_count": 20, "id": "ce2a03d8-bcbf-4c94-899a-5b773ffce70a", "metadata": {}, "outputs": [], "source": [ "#new_list = [expression for item in iterable if condition]" ] }, { "cell_type": "markdown", "id": "d7079214-a422-4cae-92f5-dc8603423826", "metadata": {}, "source": [ "Here's a breakdown of each part:\n", "- `expression`: This is the expression that you want to apply to each item in the iterable to generate the elements of the new list.\n", "- `item`: A variable that represents each item in the iterable.\n", "- `iterable`: The existing iterable from which you are generating the new list.\n", "- `condition` (optional): An optional condition that filters the items from the iterable. If specified, only items that satisfy this condition will be included in the new list.\n", "\n", "Now, let's look at some examples to illustrate list comprehensions. First, let's generate the numbers 0-9 with a list comprehension:" ] }, { "cell_type": "code", "execution_count": 21, "id": "411e3651-1e2e-4842-a50a-e5417e378956", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n" ] } ], "source": [ "squares = [x ** 2 for x in range(10)]\n", "print(squares)" ] }, { "cell_type": "markdown", "id": "b542aaa2-c437-4e2f-b513-b76bcf31069a", "metadata": {}, "source": [ "Next, use a list comprehension to filter out even numbers from the numbers list based on the condition `x % 2 == 0`:" ] }, { "cell_type": "code", "execution_count": 22, "id": "a4ab2e1a-7413-4e55-b333-a153880187c8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6, 8, 10]\n" ] } ], "source": [ "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "even_numbers = [x for x in numbers if x % 2 == 0]\n", "print(even_numbers)" ] }, { "cell_type": "markdown", "id": "04ee7e36-7249-44c5-9e7d-e8b12f6e3139", "metadata": {}, "source": [ "Or, create a list of uppercase characters from the text string while ignoring non-alphabetic characters:" ] }, { "cell_type": "code", "execution_count": 23, "id": "ec1533b0-a266-4eb3-9514-ebb57d6c465f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['I', 'A', 'M', 'Y', 'E', 'A', 'R', 'S', 'O', 'L', 'D']\n" ] } ], "source": [ "text = \"I am 12 years old!\"\n", "uppercase_chars = [char.upper() for char in text if char.isalpha()]\n", "print(uppercase_chars)" ] }, { "cell_type": "markdown", "id": "6320ef8b-1ac5-4b4f-be9c-42e662c6a0ff", "metadata": {}, "source": [ "List comprehensions can be a powerful tool to simplify code when you need to transform or filter data in lists or other iterables. They make your code more concise and easier to read while still being efficient.\n", "\n", "If you'd like further information about list comprehensions, check out this video from Socratica:" ] }, { "cell_type": "markdown", "id": "b876fa3d", "metadata": {}, "source": [ "[![Socratica: List Comprehensions](https://img.youtube.com/vi/AhSvKGTh28Q/maxresdefault.jpg)](https://youtu.be/AhSvKGTh28Q)" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md:myst" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.4" } }, "nbformat": 4, "nbformat_minor": 5 }