Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
DATA STRUCTURES Module 3 - Data Structures Python Python Basics Python Programming: From Zero to Real-World Applications

Lists in Python - Creating, Indexing, and Slicing

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to create and access lists
  • Indexing and slicing
  • Modifying list elements
Terminalpython
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []

# Indexing (0-based)
print(fruits[0])     # apple
print(fruits[-1])    # cherry (last)
print(fruits[1])     # banana

# Slicing [start:end:step]
print(numbers[0:3])   # [1, 2, 3]
print(numbers[:3])    # [1, 2, 3] (from start)
print(numbers[2:])    # [3, 4, 5] (to end)
print(numbers[::-1])  # [5, 4, 3, 2, 1] (reverse!)
print(numbers[::2])   # [1, 3, 5] (every other)

Modifying Lists

Terminalpython
fruits = ["apple", "banana", "cherry"]

# Change an element
fruits[0] = "avocado"
print(fruits)   # ['avocado', 'banana', 'cherry']

# Add elements
fruits.append("date")       # Add to end
fruits.insert(0, "apple")   # Insert at index
print(fruits)   # ['apple', 'avocado', 'banana', 'cherry', 'date']

# Remove elements
fruits.remove("avocado")    # Remove by value
popped = fruits.pop()       # Remove and return last
print(fruits)   # ['apple', 'banana', 'cherry']
print(popped)   # date

Checking Membership

Terminalpython
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)      # True
print("grape" in fruits)       # False
print("grape" not in fruits)   # True

Practical Exercise

Create a list of 5 numbers
Print the first and last element
Slice: print middle 3 elements
Reverse the list: numbers[::-1]
Add and remove elements

Key Takeaways

  • Lists are ordered, mutable (changeable) collections.
  • Indexing: [0] is first, [-1] is last.
  • Slicing: [start:end:step]. [::-1] reverses.
  • append() adds to end. insert() adds at index.
  • remove() by value. pop() removes and returns.
  • in checks membership.
Previously: Module 2 covered control flow.
Today: You learned: Master lists - the most used Python data structure.
Next: Lesson 17 covers list methods.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments