Python Lists
Lists in Python

Learning Objectives
After this lesson, you will be able to:
Create lists in Python.
Print out specific elements in a list.
Perform common list operations.
Lists
What is a list?
A list is Python's name for an array. They function very similarly to Javascript arrays.
If you want to access a specific element, you access it with bracket notations in the same way as Javascript. For example, to print 'Steve', we would write: print(my_class[2])
.
List Operations
Basic List Operations
len()
len()
To get the length of a list, use len(list_name)
. For example:
append()
append()
To add something on the end of a list, use list_name.append(item)
. For example:
insert()
insert()
To add an element in a list at a specific index, use list_name.insert(index, item)
. For example:
pop()
pop()
There are two ways to use pop()
; with no parameters or with an index. If no parameter is set, pop()
will remove the last item from a list and return it, otherwise it will remove the item at that specific index. For example:
Test it out!
Declare a list with the names of your classmates
Print out the length of that list
Add a new classmate
Print the 3rd name on the list
Delete the first name on the list
Move the last name on the list to be the second name
Answers ```python # 1. Declare a list with the names of your classmates classmates = ["James", "Tamis", "Parker", "Nhu", "Brad", "Q", "Kelly", "Paulo", "Doug"] # 2. Print out the length of that list print(len(classmates)) # 3. Add a new classmate classmates.append("Rome") print(classmates) # 4. Print the 3rd name on the list print(classmates[2]) # 5. Delete the first name on the list print(classmates.pop(0)) # 6. Move the last name on the list to be the second name classmates.insert(1, classmates.pop()) print(classmates) ```
Numerical List Operations
These actions can only be used with lists of numbers.
sum()
sum()
This is used when you want to add all the numeric items in your list. For example:
min()
and max()
min()
and max()
These will find the smallest and largest number in your list. For example:
Test it out!
Declare a list of numbers
Print out the largest difference between numbers
Print the mean of all the numbers
Answers
```python # Declare a list of numbers numberz = [4, 10, 8, 9, 77, 21, 3, 4] # Print out the largest difference between numbers big_diff = max(numberz) - min(numberz) print(big_diff) # Print the mean of all the numbers avg = sum(numberz)/len(numberz) print(avg) ```
Additional Resources
Last updated
Was this helpful?