Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Listas Anidadas | Otros Tipos de Datos
Introducción a Python

book
Listas Anidadas

Una lista anidada en Python es una lista que contiene otras sublistas como sus elementos. Esta estructura es especialmente útil para agrupar elementos relacionados dentro de una lista principal, donde cada sublista suele compartir atributos o relaciones comunes.

Para acceder a los elementos dentro de estas sublistas, se utiliza la indexación de forma secuencial — es decir, primero se selecciona el índice de la lista principal y luego el índice de la sublista. La siguiente aplicación práctica y el diagrama proporcionan una visión detallada de cómo crear y gestionar listas anidadas de manera eficaz.

Aplicación de ejemplo

Un cliente en tu tienda de comestibles ha compilado una lista de productos, donde los detalles de cada producto se almacenan en sublistas bajo nombres de variables.

Ayudaremos al cliente a acceder a los detalles de la sublista milk, agregar un nuevo producto, eliminar uno existente y ordenar toda la grocery_list.

Comencemos creando una lista y avanzando paso a paso:

# Define individual grocery items as lists containing details
bread = ["Bread", 4.80, 3, "Gluten Free"] # Item name, price, quantity, type
milk = ["Milk", 5.99, 2, "2% Milk"] # Item name, price, quantity, type
apple = ["Apple", 1.27, 12, "Fuji"] # Item name, price, quantity, type

# Create the main grocery list that contains these items
grocery_list = [bread, apple, milk]
print("Grocery List:" , grocery_list)

# Accessing and printing specific item details using indexing
print("Item:", grocery_list[2][0]) # Accesses "Milk" title
print("Price:", grocery_list[2][1]) # Accesses price of a Milk, which is 5.99
print("Quantity:", grocery_list[2][2]) # Accesses quantity of Milk, which is 2
print("Type:", grocery_list[2][3]) # Accesses type of Milk, which is "2% Milk"

# Adding a new sublist item to the grocery list
onion = ["Onions", 1.30, 10, "Yellow"]
grocery_list.append(onion)

# Removing an item from the grocery list
grocery_list.remove(bread)

# Sorting the grocery list alphabetically
grocery_list.sort()
print("Updated Grocery List:", grocery_list)
12345678910111213141516171819202122232425
# Define individual grocery items as lists containing details bread = ["Bread", 4.80, 3, "Gluten Free"] # Item name, price, quantity, type milk = ["Milk", 5.99, 2, "2% Milk"] # Item name, price, quantity, type apple = ["Apple", 1.27, 12, "Fuji"] # Item name, price, quantity, type # Create the main grocery list that contains these items grocery_list = [bread, apple, milk] print("Grocery List:" , grocery_list) # Accessing and printing specific item details using indexing print("Item:", grocery_list[2][0]) # Accesses "Milk" title print("Price:", grocery_list[2][1]) # Accesses price of a Milk, which is 5.99 print("Quantity:", grocery_list[2][2]) # Accesses quantity of Milk, which is 2 print("Type:", grocery_list[2][3]) # Accesses type of Milk, which is "2% Milk" # Adding a new sublist item to the grocery list onion = ["Onions", 1.30, 10, "Yellow"] grocery_list.append(onion) # Removing an item from the grocery list grocery_list.remove(bread) # Sorting the grocery list alphabetically grocery_list.sort() print("Updated Grocery List:", grocery_list)
copy

El diagrama a continuación ilustra la estructura de lista anidada de grocery_list. Cada elemento de la lista, como milk, apple y bread, es a su vez una lista que contiene los detalles específicos de un artículo.

Por ejemplo, para acceder al precio de la leche, que se almacena en la sublista milk, se utiliza la sintaxis grocery_list[2][1]. Aquí, grocery_list[2] selecciona la sublista milk, y grocery_list[2][1] accede al segundo elemento de esa sublista — el precio.

Tarea

Swipe to start coding

Actualización de una lista de inventario para la sección de verduras de una tienda de comestibles eliminando un artículo, agregando dos nuevos artículos y ordenando la lista alfabéticamente sin duplicados.

  • Crear una variable vegetables con la lista ["tomatoes", "potatoes", "onions"].
  • Eliminar "onions" de la lista.
  • Agregar "carrots" a la lista si aún no está presente.
  • Agregar "cucumbers" a la lista si aún no está presente.
  • Ordenar la lista alfabéticamente.

Requisitos de salida

  • Imprimir la lista actualizada de verduras: "Updated Vegetable Inventory: <$vegetables>".
  • Si "carrots" ya está en la lista, imprimir: "Carrots are already in the list."
  • Si "cucumbers" ya está en la lista, imprimir: "Cucumbers are already in the list."

Solución

# Task 1: Assign `vegetables` to a list of strings containing "tomatoes", "potatoes", and "onions"
vegetables = ["tomatoes", "potatoes", "onions"]

# Task 2: Remove "onions" from the list
vegetables.remove("onions")

# Task 3: Add "carrots" string to the list if it's not already present
if "carrots" not in vegetables:
vegetables.append("carrots")
else:
print("Carrots are already in the list.")

# Task 4: Check if "cucumbers" are in the list and add them if they're not
if "cucumbers" not in vegetables:
vegetables.append("cucumbers")
else:
print("Cucumbers are already in the list.")

# Task 5: Sort the list alphabetically
vegetables.sort()

# Print the updated and sorted vegetable list
print("Updated Vegetable Inventory:", vegetables)
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 2

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt