Lists
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Lists
Definition: Lists are ordered collections that can store multiple values in a single variable. They are one of the most versatile and frequently used data structures in Python.
Why: Lists are a main data structure topic because they allow you to manage groups of related data (like a list of usernames or prices) efficiently using a single name.
Syntax
list_name = [item1, item2, item3]
Example
fruits = ["apple", "banana", "mango"]
print(fruits)
# Accessing an item
print(fruits[0])
# Adding an item
fruits.append("orange")
print(fruits)
Explanation
- Square Brackets: Lists are defined using
[ ]. - Indexing: Items are accessed by their position, starting at
0(sofruits[0]is "apple"). - Append: The
.append()method adds a new item to the very end of the list.
Useful List Features
- Change Values: You can update an item by referring to its index (e.g.,
fruits[1] = "cherry"). - Add Items: Use
append()to add to the end orinsert()to add at a specific spot. - Remove Items: Use
remove()to delete a specific value orpop()to remove an item at a certain index. - Looping: You can use a
forloop to process each item in the list one by one.
Key Notes
- Lists are mutable, meaning you can change, add, and remove items after the list has been created.
- A single list can hold different data types (e.g., a mix of strings, integers, and booleans).
- Lists maintain the order of items as they were inserted.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute