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 contains three items. Lists can grow or shrink dynamically, and you can update them at any time.
Accessing List Items
Python lists are zero-indexed, meaning:
- 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:
-1refers to the last item-2refers 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
Lessons in this chapter Β· Python Programming Review
- 1. Variables and Data Types
- 2. Expressions and Arithmetic
- 3. String Operations
- 4. Lists in Python
- 5. List Methods and Slicing
- 6. Tuples and Sets
- 7. Dictionaries - Keys and Values
- 8. Dictionary Methods and Nesting
- 9. Conditional Statements (if, elif, else)
- 10. Loops - for and while
- 11. Control Flow & Data Structures Recap
- 12. Multiple-choice quiz
- 13. Loop Controls (break, continue, pass)
- 14. Functions - Defining and Calling
- 15. Function Arguments and Return Values
- 16. Variable Scope and Nested Functions
- 17. Exception Handling with try/except
- 18. File Reading and Writing
- 19. CSV File Parsing
- 20. Using Built-in Modules (math, random, datetime)
- 21. Importing External Modules
- 22. Fill-in-the-blank quiz
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