Master Python Lists: Access, Modify, Sort, and Slice Explained
This tutorial explains Python lists—how to create them, access elements by index, modify items, add or remove entries, sort permanently or temporarily, generate numeric lists with range, perform basic statistics, and use slicing to extract or copy sub‑lists.
In Python, a list is defined using square brackets, e.g., a = ['Python', 'C', 'Java'] . List elements are ordered and can be accessed by zero‑based indices; a[0] returns 'Python'. Negative indices allow reverse access, such as a[-3] .
Elements can be modified by assignment, e.g., a[2] = 'R' . Adding elements uses append() or insert() , while removal can be done with del , remove() , or pop() . The length of a list is obtained with len(a) .
Lists can be sorted permanently with sort() (optionally reverse=True ) or temporarily with the built‑in sorted() function. The reverse() method reverses the order in place.
Creating numeric lists is easy with list(range(start, stop, step)) . Basic statistics such as min() , max() , and sum() can be applied to numeric lists.
Slicing extracts sub‑lists: a[1:3] , a[:2] , a[2:] , or a[-3:] . Copying a list via slicing ( b = a[:] ) creates an independent list, whereas simple assignment ( b = a ) creates a reference.
<code>a = ['Python','C','Java']
print(a[0]) # Python
print(a[-3]) # Python
a[2] = 'R'
print(a) # ['Python', 'C', 'R']
a.append('Ruby')
print(a) # ['Python', 'C', 'R', 'Ruby']
a.insert(1, 'Ruby')
print(a) # ['Python', 'Ruby', 'C', 'R', 'Ruby']
del a[1]
print(a) # ['Python', 'C', 'R', 'Ruby']
a.remove('Ruby')
print(a) # ['Python', 'C', 'R']
b = a.pop(1)
print(a) # ['Python', 'R']
print(b) # C
c = list(range(1,10))
print(c) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(min(c), max(c), sum(c)) # 1 9 45
a = ['Python', 'Ruby', 'C', 'Java']
a.sort()
print(a) # ['C', 'Java', 'Python', 'Ruby']
a.sort(reverse=True)
print(a) # ['Ruby', 'Python', 'Java', 'C']
print(sorted(a)) # temporary sorted list
print(a[::-1]) # reverse order without modifying
# slicing examples
print(a[1:3]) # ['Python', 'Ruby']
print(a[:2]) # ['C', 'Java']
print(a[2:]) # ['Python', 'Ruby']
print(a[-3:]) # ['Java', 'Python', 'Ruby']
# copy via slicing
b = a[:]
a.append('CSS')
print(a) # original list with CSS
print(b) # copy unchanged
</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.