In this lesson, we will focus on Python Lists and JavaScript Arrays (a type of list). The emphasis will be on completing hacks in both languages.
Time Expectations:
- ⏳ Popcorn Hacks: ~20-30 minutes in class
- 📚 Homework: ~30 minutes, consisting of 3 tasks
- Submission: Remember to submit both the popcorn hacks we gave to you in-class and the actual homework that was assigned.
Good luck and happy coding!
In the context of Python, a list is a collection of items that are both ordered and mutable (changeable). Python lists support a variety of data types, such as:
- Integers (whole numbers)
- Strings
- Decimal numbers
To create a Python list, use square brackets []. The items inside the brackets should be separated by commas.
my_list = [1, 2, 3, 'string', 4.78]
print(my_list) # This will print the contents of the list.
[1, 2, 3, 'string', 4.78]
my_list = [1, 2, 3, 'string', 4.78]
first_item = my_list[0] # 1
last_item = my_list[-1] # 4.78 (negative index counts from the end)
my_list[1] = 'banana' # Now my_list is [1, 'banana', 3, 'string', 4.78].
- To add an item to the end of your list, use the
.append()method. This is typically placed after the name of your list, since the period (.) allows you to access certain properties within the list. - You can also use the
.insert()method to insert the element at a particular index. Format it as(index #, insert something here). - To remove an element, use the
.remove()method, which removes the first occurrence of the specified element in the list.
my_list = [1, 2, 3, 'string', 4.78]
my_list.append('orange') # Adds 'orange' to the end
my_list.insert(2, 'grape') # Inserts 'grape' at index 2
my_list.remove(3) # Removes 3
print(my_list) # Output the modified list
fruits = ['apple', 'banana', 'cherry']
# Check for existence
if 'banana' in fruits:
print("Banana is in the list!")
else:
print("Banana is not in the list.")
Banana is in the list!
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit) # For loop
i = 0
while i < len(fruits):
print(fruits[i]) # While loop
i += 1
If you’re a little lost on how to use a Python list, below is an example that combines some of the operations and topics discussed in 3.10.
# Creating a list of colors
colors = ['red', 'blue', 'green']
# Modifying the list
colors.append('yellow') # Adds 'yellow' to the end
colors.insert(1, 'orange') # Inserts 'orange' at index 1
print(colors) # Output: ['red', 'orange', 'blue', 'green', 'yellow']
# Removing an element
colors.remove('blue') # Removes 'blue'
print(colors) # Output: ['red', 'orange', 'green', 'yellow']
# Checking for existence
if 'orange' in colors:
print("Orange is in the list!")
# Iterating over the list
for color in colors:
print(color) # Prints each color
- Create a list of your choosing.
- Remove the last element or item in that list.
- Remove the first element or item in that list.
- Remove an element or item in the list that has a different index than the first or last element/item.
- Print the final list.