Master Python Lists: Essential Operations and Practical Examples
This tutorial introduces Python lists, explaining their characteristics, how to create them, and covering the most common operations such as indexing, slicing, concatenation, repetition, membership testing, built‑in functions, and list methods with clear code examples.
List Characteristics
A mutable ordered collection that can store items of any type, including other lists.
Defined with square brackets [] and items separated by commas.
Elements are accessed by zero‑based indices and support negative indexing.
Creating Lists
Simply place comma‑separated values inside brackets:
list1 = [1, 2, 3, 4, 5]
list2 = [12, "kkk", ["12", "bb"]]Basic List Operations
Access elements, get length, and combine lists:
# Indexing
list1[1] # 2
list1[-1] # 5
len(list1) # 5
# Concatenation
list3 = list1 + list2
# Repetition
list4 = ["hello world"] * 3
# Membership test
7 in list1 # False
7 in list2 # TrueIterating Over a List
for e in list1:
print(e)
# Output: 1 2 3 4 5Common Built‑in Functions
max(list1) # 5
min(list1) # 1
list1.index(2) # 1
sum(list1) # 15
sum(list1)/len(list1) # 3.0List Methods
append(item)– add an element to the end. count(item) – count occurrences. extend(iterable) – extend list with another iterable. pop(index) – remove and return element at index. remove(item) – remove first matching element. reverse() – reverse in place. sort() – sort in ascending order.
list1.append(15)
list1
# [1, 2, 3, 4, 5, 15]
list4 = [1,2,3,5,6,1,23,5,6,1,2,3,4,5,15]
list4.pop(1) # 2
list4.remove(5) # removes first 5
list4.reverse()
list4.sort()
list4
# [1, 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 15, 23]Slicing and Advanced Indexing
# Slice (start:stop)
list4[3:6] # [2, 3, 3]
# Slice with step
list4[3:10:2] # [2, 3, 5]
# Reverse slice
list4[::-1] # [23, 15, 6, 6, 5, 5, 4, 3, 3, 2, 1, 1, 1]
# Assign to slice
list4[3:6] = [22, 22, 22]
list4
# [1, 1, 1, 22, 22, 22, 4, 5, 5, 6, 6, 15, 23]Conversion to Set
unique = set(list4) # {1, 2, 3, 4, 5, 6, 15, 22, 23}
len(unique) # 9Next Steps
The next article in this series will cover Python dictionaries, a more powerful data structure for key‑value mapping.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
