Python List Operations: Indexing, Slicing, and Modification
This article explains how Python lists can contain mixed data types, demonstrates accessing elements with positive and negative indexes, shows slicing techniques, and illustrates various ways to add, remove, replace, and manipulate list items using built‑in functions and methods.
The article introduces Python lists, emphasizing that list elements may be of any type such as strings, tuples, dictionaries, functions, file objects, or numbers.
Lists can be accessed by index from the start (positive numbers) or from the end (negative numbers), and slices can be used to obtain sub‑lists.
>> x = ["first","sec","third","fourth"]
>> x[0] returns 'first'
>> x[1] returns 'sec'
>> x[2] returns 'third'
>> x[3] returns 'fourth'
>> x[0:3] yields ['first', 'sec', 'third']
>> x[0:4] yields ['first', 'sec', 'third', 'fourth']
>> x[-1] returns 'fourth'
>> x[-2] returns 'third'
Positive indexes start at 0 for the first element, while negative indexes start at -1 for the last element.
Positive index
0
1
2
3
Negative index
-4
-3
-2
-1
Elements can be added, removed, or replaced, and slices can be assigned new values, causing the list size to adjust automatically.
>> x = [1,2,3,4,5,6,7,8,9]
>> x[1] = "two"
>> x[8:9] = []
>> x results in [1, 'two', 3, 4, 5, 6, 7, 8]
>> x[5:7] = [6.0,6.5,7.0]
>> x becomes [1, 'two', 3, 4, 5, 6.0, 6.5, 7.0, 8]
If the new slice size differs from the original, the list automatically resizes.
Common list operations include built‑in functions ( len , max , min ), operators ( in , + , * ), the del statement, and methods such as append , count , extend , index , insert , pop , remove , reverse , and sort .
>> len(x) returns 9
>> [-1,0] + x yields [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> x.reverse() changes the list to [9, 8, 7, 6, 5, 4, 3, 2, 1]
The + and * operators create new lists, leaving the original unchanged; list methods are invoked using the dot notation, e.g., x.method(arguments) .
----------------------end---------------------
Recommended reading:
Shell Script: case statement
Shell Script MySQL Deployment
Redis Common Interview Questions
Practical Playbook: Bulk Password Change
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.