Lists Basics
A list in Python is a collection of items that are ordered and changeable. Lists allow you to store multiple values in a single variable, making them a powerful tool for handling sequences of data.
Lists are defined using square brackets ([]
) and can contain elements of different data types, including integers, strings, floats, and even other lists.
Creating Lists
To create a list in Python, simply enclose a series of elements in square brackets, separated by commas:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Creating a list of strings
fruits = ["apple", "banana", "cherry"]
# Creating a mixed-type list
mixed_list = [42, "hello", 3.14, True]
Accessing Elements in a List
Each element in a list has an index starting from 0
. You can access elements using square brackets and the index:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: cherry
Negative Indexing
Python supports negative indexing, which allows you to access elements from the end of the list:
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana
Checking List Length
Use the len()
function to find out how many elements a list contains:
print(len(fruits)) # Output: 3
Exercise: Try It Yourself!
Task 1: Creating and Accessing Lists
- Create a list named
colors
that contains the colors:red
,green
, andblue
. - Print the second item in the
colors
list. - Print the last item using negative indexing.
Task 2: List Length
Write a program that:
- Creates a list of five favorite foods.
- Prints the length of the list.
Next, we'll dive deeper into how to manipulate and modify lists in Python!