Arrays: Lists
Let’s move on to arrays. Lists allow you to collect, organize, and manipulate sequences of data.
What is a List?
A list is a collection of items, called elements, that are ordered and changeable. Lists are created by placing elements inside square brackets «[ ]», separated by commas.
#Example: Creating a list
creatures = ["unicorn", "mermaid", "griffon"]
print(creatures)
In this example, a list named creatures is created with three elements: "unicorn", "mermaid", and "griffon".
Accessing List Elements
Elements in a list can be accessed by their index, which starts at 0. You can use square brackets with the index to access an element.
#Example: Accessing list elements
creatures = ["unicorn", "mermaid", "griffon"]
print(creatures[0]) # Output: unicorn
print(creatures[1]) # Output: mermaid
print(creatures[2]) # Output: griffon
In this example, elements are accessed by their indices:
0 for "unicorn"
1 for "mermaid"
2 for "griffon"
Modifying List Elements
Lists are mutable, meaning you can change their elements. You can modify elements by accessing them through their index and assigning a new value.
#Example: Modifying list elements
creatures = ["unicorn", "mermaid", "griffon"]
creatures[1] = "pegasus"
print(creatures) # Output: ["unicorn", "pegasus", "griffon"]
In this example, the second element "mermaid" is replaced with "pegasus".
Adding Elements to a List
You can add elements to a list using the append() method, which adds an element to the end of the list.
#Example: Adding elements to a list
creatures = ["unicorn", "mermaid", "griffon"]
creatures.append("dragon")
print(creatures) # Output: ["unicorn", "mermaid", "griffon", "dragon"]
In this example, "dragon" is added to the end of the creatures list.
Removing Elements from a List
You can remove elements from a list using the remove() method, which removes the first occurrence of a specified element.
#Example: Removing elements from a list
creatures = ["unicorn", "mermaid", "griffon"]
creatures.remove("mermaid")
print(creatures) # Output: ["unicorn", "griffon"]
In this example, "mermaid" is removed from the creatures list.
Practical Application
In the Archive of Arrays, you must manage collections of items.
Destructive Spells:
• Firenium
• Chaostos
• Tsunamilus
⋆˖⁺‧₊ Create a list of Destructive Spells you've learned, add any other spell using append() and display all spells. ₊‧⁺˖⋆
Sample Output:
Destructive Spells:
1 spell: Firenium
2 spell: Chaostos
3 spell: Tsunamilus
4 spell: Quenaretum