Approx. read time: 3.4 min.
Post: Learn Python Lists
Lesson on Lists in Python
Lists in Python are a versatile and powerful tool for storing collections of items. They are similar to arrays in other programming languages but are more flexible as they can contain items of different types. You can add, remove, and iterate over elements in a list with ease. Let’s dive deeper into the basics of lists, how to manipulate them, and see some practical examples.
Creating and Manipulating Lists
To create a list, you simply use square brackets []
. You can initialize an empty list or create a list with initial elements.
Example 1: Creating and Appending to a List
# Initializing an empty list
mylist = []
# Appending elements to the list
mylist.append(1)
mylist.append(2)
mylist.append(3)
# Accessing elements in the list by index
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# Iterating over the list and printing elements
for x in mylist:
print(x) # prints 1, 2, 3
Accessing Elements in a List – Learn Python Lists
Lists in Python are zero-indexed, meaning the first element is at index 0. Accessing an element at an index that does not exist will raise an IndexError
.
Example 2: Accessing List Elements and Handling Index Errors
mylist = [1, 2, 3]
# Trying to access an element at an index that doesn't exist
try:
print(mylist[10]) # This will raise an IndexError
except IndexError as e:
print(f"Error: {e}")
Practical Exercise
In this exercise, you’ll practice adding elements to lists and accessing specific elements. You’ll need to add numbers and strings to their respective lists using the append
method. Additionally, you’ll extract the second name from a list of names.
Exercise: Fill and Access Lists
# Initialize empty lists
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# Adding numbers to the 'numbers' list
numbers.append(1)
numbers.append(2)
numbers.append(3)
# Adding strings to the 'strings' list
strings.append("hello")
strings.append("world")
# Accessing the second name in the 'names' list
second_name = names[1]
# Printing the lists and the second name
print(numbers) # Output: [1, 2, 3]
print(strings) # Output: ["hello", "world"]
print(f"The second name on the names list is ") # Output: The second name on the names list is Eric
Explanation – Learn Python Lists
- Creating Lists:
numbers
,strings
, andnames
are initialized. - Appending Elements: Elements are added to
numbers
andstrings
using theappend
method. - Accessing Elements: The second element of
names
is accessed usingnames[1]
. - Output: The contents of the lists and the second name are printed.
Additional Examples
Example 3: Mixed Data Types in Lists
lists can contain elements of different data types, including other lists.
mixed_list = [1, "hello", 3.14, [4, 5, 6]]
print(mixed_list) # Output: [1, 'hello', 3.14, [4, 5, 6]]
# Accessing a sub-list element
print(mixed_list[3][1]) # Output: 5
Example 4: List Comprehensions
# Creating a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Conclusion – Learn Python Lists
Lists are a fundamental data structure in Python, providing a flexible and efficient way to handle collections of items. Whether you’re adding elements, iterating over them, or accessing specific items, lists offer a straightforward syntax that makes them easy to use.
For hands-on practice, you can use online Python compilers like Trinket.io to run and modify the examples provided in this lesson. Happy coding!
Additional Exercise – Learn Python Lists
In this exercise, you will need to create a list of the first 5 even numbers and a list of the first 5 odd numbers. Then, combine these two lists into a single list and print the combined list.
Exercise:
# Create lists of even and odd numbers
even_numbers = []
odd_numbers = []
# Add first 5 even numbers to the 'even_numbers' list
for i in range(2, 11, 2):
even_numbers.append(i)
# Add first 5 odd numbers to the 'odd_numbers' list
for i in range(1, 10, 2):
odd_numbers.append(i)
# Combine both lists
combined_list = even_numbers + odd_numbers
# Print the combined list
print(combined_list) # Output: [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
Answer Key:
# Expected output
# [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]