Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“‹ Python List: Access Elements

Python List Access Elements - Complete Guide

Learn how to access elements in Python lists using indexing, negative indexing, and slicing.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • Welcome: Accessing List Elements
  • Positive Indexing
  • Negative Indexing
  • List Slicing
  • Advanced Slicing Techniques
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • Positive indexing — accessing elements from the beginning
  • Negative indexing — accessing elements from the end
  • List slicing — extracting multiple elements at once
  • Advanced slicing — step values and reversing lists
  • Common mistakes — and how to avoid them

Welcome: Accessing List Elements

šŸ“– Think of it this way: A list is like a row of numbered lockers. Each locker has a position (index). You can access items by their position number. You can also look at a range of lockers at once (slicing).

Once you have created a list, you need to know how to access its elements. Python provides several powerful ways to access list elements: positive indexing, negative indexing, and slicing.

šŸ’” Key insight: Accessing elements in a list is one of the most common operations in Python. Understanding these techniques will make you a more efficient programmer.

Positive Indexing

1

Accessing from the Beginning

Python uses 0-based indexing. The first element is at index 0, the second at index 1, and so on.

# Create a list
fruits = ["apple", "banana", "cherry", "mango", "orange"]

# Accessing elements using positive indices
print(fruits[0])   # apple (first element)
print(fruits[1])   # banana (second element)
print(fruits[2])   # cherry (third element)
print(fruits[3])   # mango (fourth element)
print(fruits[4])   # orange (fifth element)

# Visual representation:
# Index:   0         1         2         3         4
#       ["apple", "banana", "cherry", "mango", "orange"]

# Using in a loop
for i in range(len(fruits)):
    print(f"Index {i}: {fruits[i]}")

Key points:

  • The first element is always at index 0
  • The last element is at index len(list) - 1
  • Accessing an index that doesn't exist causes IndexError

āœ… Quick Check: What index does the last element of a list with 5 items have? (Answer: 4)

Negative Indexing

2

Accessing from the End

Python allows you to access elements from the end using negative indices. The last element is at index -1, the second last at -2, and so on.

fruits = ["apple", "banana", "cherry", "mango", "orange"]

# Accessing elements using negative indices
print(fruits[-1])   # orange (last element)
print(fruits[-2])   # mango (second last)
print(fruits[-3])   # cherry (third last)
print(fruits[-4])   # banana (fourth last)
print(fruits[-5])   # apple (first element)

# Visual representation:
# Index:   0         1         2         3         4
#       ["apple", "banana", "cherry", "mango", "orange"]
# Index:   -5        -4        -3        -2        -1

# Using in a loop
for i in range(1, len(fruits) + 1):
    print(f"Index {-i}: {fruits[-i]}")

Key points:

  • -1 is always the last element
  • -len(list) is always the first element
  • Negative indexing is useful when you don't know the list length

āœ… Quick Check: What index accesses the last element of a list? (Answer: -1)

List Slicing

3

Extracting Sublists

Slicing allows you to extract a subrange of elements from a list. The syntax is list[start:stop:step].

fruits = ["apple", "banana", "cherry", "mango", "orange", "grape", "kiwi"]

# Basic slicing
print(fruits[1:4])    # ["banana", "cherry", "mango"] (index 1 to 3)
print(fruits[:4])     # ["apple", "banana", "cherry", "mango"] (start to index 3)
print(fruits[2:])     # ["cherry", "mango", "orange", "grape", "kiwi"] (index 2 to end)
print(fruits[:])      # ["apple", "banana", "cherry", "mango", "orange", "grape", "kiwi"] (full copy)

# Slicing with step
print(fruits[0:6:2])  # ["apple", "cherry", "orange"] (every 2nd element)
print(fruits[1:6:2])  # ["banana", "mango", "grape"] (every 2nd element starting at 1)

# Negative slicing
print(fruits[-3:])    # ["orange", "grape", "kiwi"] (last 3 elements)
print(fruits[:-2])    # ["apple", "banana", "cherry", "mango", "orange"] (all except last 2)
print(fruits[-4:-1])  # ["mango", "orange", "grape"] (index -4 to -2)

# Reversing a list
print(fruits[::-1])   # ["kiwi", "grape", "orange", "mango", "cherry", "banana", "apple"]

Slicing rules:

  • start is included, stop is excluded
  • If start is omitted, it starts at 0
  • If stop is omitted, it goes to the end
  • If step is omitted, it's 1
  • Slicing creates a new list (original is unchanged)

āœ… Quick Check: What does list[:] do? (Answer: It creates a full copy of the list)

Advanced Slicing Techniques

4

Powerful Slicing Patterns

Here are some advanced slicing techniques that are extremely useful:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Get every 3rd element
print(numbers[::3])   # [0, 3, 6, 9, 12, 15]

# Get every 4th element starting from index 2
print(numbers[2::4])  # [2, 6, 10, 14]

# Get first 5 elements
print(numbers[:5])    # [0, 1, 2, 3, 4]

# Get last 5 elements
print(numbers[-5:])   # [11, 12, 13, 14, 15]

# Get elements from index 3 to 10 (excluding 10)
print(numbers[3:10])  # [3, 4, 5, 6, 7, 8, 9]

# Get elements from index 3 to 10 with step 2
print(numbers[3:10:2]) # [3, 5, 7, 9]

# Reverse the list (most common way)
print(numbers[::-1])  # [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# Get alternating elements (even positions)
print(numbers[::2])   # [0, 2, 4, 6, 8, 10, 12, 14]

# Get alternating elements (odd positions)
print(numbers[1::2])  # [1, 3, 5, 7, 9, 11, 13, 15]

Practical patterns:

  • list[::-1] — reverse the list
  • list[::2] — get elements at even indices
  • list[1::2] — get elements at odd indices
  • list[:n] — get first n elements
  • list[-n:] — get last n elements

āœ… Quick Check: How do you get the last 3 elements of a list? (Answer: list[-3:])

Common Mistakes to Avoid

5

Watch Out For These!

āŒ Mistake 1: Index Out of Range

Accessing an index that doesn't exist:

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

# WRONG
print(fruits[3])  # IndexError: list index out of range

# CORRECT
print(fruits[2])  # cherry

# Always check length
if len(fruits) > 3:
    print(fruits[3])

āŒ Mistake 2: Using Negative Index Incorrectly

Remember -1 is the last element, not the first:

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

# WRONG (thinking -1 is first)
print(fruits[-1])  # cherry (not apple!)

# CORRECT
print(fruits[0])   # apple
print(fruits[-3])  # apple (if you need negative indexing)

āŒ Mistake 3: Modifying List While Accessing

Don't change the list while you're accessing it:

# WRONG (can cause unexpected behavior)
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
    if numbers[i] % 2 == 0:
        numbers.pop(i)

# CORRECT (access safely)
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
    print(numbers[i])

āŒ Mistake 4: Confusing Copy vs. Reference

Using = instead of copy() when you want a new list:

original = [1, 2, 3, 4, 5]

# WRONG (creates a reference, not a copy)
copy = original
copy[0] = 99
print(original)  # [99, 2, 3, 4, 5] — changed!

# CORRECT (creates a new list)
copy = original.copy()
copy[0] = 99
print(original)  # [1, 2, 3, 4, 5] — unchanged

āœ… Quick Check: What error do you get when you access an index that doesn't exist? (Answer: IndexError)

Try It Yourself!

Experiment with accessing list elements directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
LIST ACCESS PRACTICE
========================================

Fruits: ['apple', 'banana', 'cherry', 'mango', 'orange', 'grape', 'kiwi']

1. POSITIVE INDEXING
First fruit: apple
Third fruit: cherry
Last fruit: kiwi

2. NEGATIVE INDEXING
Last fruit: kiwi
Second last: grape
First fruit: apple

3. SLICING
First 3 fruits: ['apple', 'banana', 'cherry']
Last 3 fruits: ['orange', 'grape', 'kiwi']
Middle fruits: ['cherry', 'mango', 'orange']
Every 2nd fruit: ['apple', 'cherry', 'orange', 'kiwi']
Reversed: ['kiwi', 'grape', 'orange', 'mango', 'cherry', 'banana', 'apple']

āœ… Explore list access!
šŸ†

šŸŽ‰ You've Mastered List Access!

You understand positive indexing, negative indexing, and slicing. These are essential skills for working with Python lists!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about accessing list elements:

1. What index does the first element in a list have?
2. How do you access the last element of a list?
3. What does list[:3] return?
4. How do you reverse a list using slicing?
5. What error occurs when you access an index that doesn't exist?

Frequently Asked Questions

šŸ¤” What is the difference between indexing and slicing? ā–¼

Indexing accesses a single element (e.g., list[0]). Slicing accesses a range of elements and returns a new list (e.g., list[0:3]). Slicing creates a copy; indexing does not.

šŸ”§ Can I use negative indices in slicing? ā–¼

Yes! Negative indices work in slicing too. For example, list[-3:] gets the last 3 elements, and list[-5:-2] gets elements from the 5th last to the 3rd last.

šŸ“ What happens if the start index is greater than the stop index? ā–¼

If start > stop and you don't use a negative step, the slice will be empty. For example, list[5:2] returns []. Use a negative step to go backwards: list[5:2:-1].

šŸ“Š Does slicing modify the original list? ā–¼

No! Slicing creates a new list and does not modify the original list. The original list remains unchanged. This is different from methods like append() or pop().

⚔ Can I assign values using slicing? ā–¼

Yes! You can assign to a slice to replace elements. For example, list[1:3] = ['x', 'y'] replaces elements at indices 1 and 2. You can even change the list length by assigning a different number of elements.

šŸŽÆ What's the fastest way to reverse a list? ā–¼

The fastest and most Pythonic way is list[::-1]. This creates a new reversed list. If you want to reverse in place, use list.reverse().

šŸ“š Where to Go From Here

Now that you've mastered accessing list elements, here are the next topics to explore:

šŸ“‹ List Functions

Explore all built-in list functions and methods.

Learn More →

šŸ“‹ Iterate Lists

Learn different ways to loop through lists.

Learn More →

šŸ“‹ List Comprehension

Learn the powerful list comprehension technique.

Learn More →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • Python Data Types Interview Questions
Previous: List in Python Next: List Functions →