Python Lists: Arrays, Methods and Iteration
Learn everything about Python lists. Discover how to create, slice, modify, and iterate through arrays in Python natively.
Overview
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data.
Lists are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.
You can append, remove, sort, and slice lists efficiently.
Code Example
Demonstrating initialization, indexing, modification and standard list iteration.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add item
fruits[1] = "mango" # Change item
fruits.sort() # Alphabetical sort
print(f"List: {fruits}")
print(f"First fruit: {fruits[0]}")
print(f"Total fruits: {len(fruits)}")List: ['apple', 'cherry', 'mango', 'orange']
First fruit: apple
Total fruits: 4Real-world Use Cases
- Holding ordered collections like a queue of tasks
- Accumulating data points over time
- Implementing stacks and queues
Frequently Asked Questions
What is a list comprehension?
It is a shorter syntax when you want to create a new list based on the values of an existing list. Example: [x for x in fruits if "a" in x]
What is the difference between list and tuple?
Lists are mutable (changeable) while tuples are immutable (unchangeable). Tuples use parentheses ().