Lecture

Lists in Python

In Python, a list is a collection of items that are ordered and can be changed. Lists are one of the most common data structures in data analysis.

A list can store many kinds of data such as numbers, strings, or even other lists.


Creating a List

To create a list, use square brackets [] and separate the items with commas:

Creating a List
fruits = ["apple", "banana", "cherry"]

This list has 3 items. Lists can grow or shrink dynamically, and you can update them anytime.


Accessing List Items

Python lists are zero-indexed. This means:

  • The first item is at index 0
  • The second item is at index 1
  • And so on...

You can also use negative indexing to access items from the end:

  • -1 refers to the last item
  • -2 refers to the second-to-last item

Let's look at some real examples in the code block below.


Code Examples

Here are some examples of how to access list items:

Accessing List Items
# Creating a list of cities cities = ["New York", "Chicago", "Los Angeles", "Houston"] # Accessing the first item print("First city:", cities[0]) # New York # Accessing the third item print("Third city:", cities[2]) # Los Angeles # Accessing the last item using negative index print("Last city:", cities[-1]) # Houston # Accessing the second-to-last item print("Second-to-last city:", cities[-2]) # Los Angeles

Why Lists Are Important

Lists allow you to store and organize data in a flexible way.

Indexing is essential when retrieving specific values for analysis, filtering, or looping through data.

Quiz
0 / 1

Lists in Python are zero-indexed, meaning the first item can be accessed using the index 1.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result