Python lists form the backbone of many programs. A list holds a collection of items and offers flexibility in how those items are stored, modified, and retrieved. Unlike arrays in other languages, lists in Python can contain items of mixed data types, such as integers, strings, floats, and even other lists.
A list in Python refers to an ordered group of items placed within square brackets. Each item in the list is separated by a comma. Lists can grow, shrink, and be rearranged.
Example:
fruits = ["apple", "banana", "cherry"] In this example, the variable fruits contains three string elements.
There are multiple ways to create a list in Python. Each method suits different use cases.
The most direct way to create a list is by placing elements inside square brackets.
numbers = [1, 2, 3, 4, 5] list() ConstructorThe list() constructor converts other iterable data types like tuples or strings into a list.
data = list((10, 20, 30))
chars = list("python") Lists can be initialized without any items.
empty_list = []
alt_empty = list() Each item in a list has a position, known as an index. Indexing starts from zero.
Example:
letters = ['a', 'b', 'c', 'd']
print(letters[0]) # Output: 'a'
print(letters[3]) # Output: 'd' Negative indexing allows access from the end of the list.
print(letters[-1]) # Output: 'd' Individual elements can be retrieved using square bracket notation with an index.
Access by position:
students = ['John', 'Alice', 'Mark']
second = students[1] # 'Alice' Access using negative indexing:
last_student = students[-1] # 'Mark' Slicing creates a new list from part of an existing one.
colors = ['red', 'green', 'blue', 'yellow']
primary = colors[0:3] # ['red', 'green', 'blue'] Syntax:
list[start:stop:step] Skipping elements with a step:
alternate = colors[::2] # ['red', 'blue'] Values in a list can be changed using index assignment.
scores = [10, 20, 30]
scores[1] = 25 # Now scores is [10, 25, 30] Lists allow duplicate elements. Each element can be modified independently.
Elements can be inserted in several ways:
append()Adds an item at the end.
items = [1, 2, 3]
items.append(4) # [1, 2, 3, 4] insert()Places an item at a specific index.
items.insert(1, 1.5) # [1, 1.5, 2, 3, 4] extend()Combines another iterable with the list.
items.extend([5, 6]) # [1, 1.5, 2, 3, 4, 5, 6] Python provides several methods to remove items from a list.
remove()Deletes the first occurrence of a value.
names = ['Tom', 'Jerry', 'Tom']
names.remove('Tom') # ['Jerry', 'Tom'] pop()Removes by index and returns the item.
names.pop(1) # 'Tom' is removed from index 1 del StatementDeletes by index without returning the value.
del names[0] List comprehension offers a shorter syntax for generating new lists.
squares = [x * x for x in range(5)] # [0, 1, 4, 9, 16] It improves readability and reduces lines of code.
Filtering conditions can be added.
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8] A list can contain another list, forming a multi-dimensional structure.
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][1]) # 4 Such structures are useful in data science, simulations, and more.
len([10, 20, 30]) # 3 20 in [10, 20, 30] # True for fruit in ['apple', 'banana']:
print(fruit) values = [3, 1, 4, 2]
values.sort() # [1, 2, 3, 4] values.sort(reverse=True) # [4, 3, 2, 1] values.reverse() # [1, 2, 3, 4] becomes [4, 3, 2, 1] A simple assignment shares the reference.
a = [1, 2, 3]
b = a # b references the same list To copy:
copy = a[:] Or use:
copy = list(a)
copy = a.copy() All items can be removed using:
data = [1, 2, 3]
data.clear() # [] From beginners to advanced developers, list operations play a central role in efficient coding. Understanding how to create, modify, and manipulate lists simplifies many programming tasks and ensures cleaner, more efficient scripts.
Also Read:
Once upon a time, accounting desks were buried under folders, binders, paper trails, and drawer…
Screens blink. Fingers tap. Voices whisper commands into thin air and machines obey. In this…
In a world where customers check online before buying, a single negative review can trigger…
DevOps keeps marching forward. Tools evolve. Culture matures. Delivery pipelines stretch across cloud edges, AI…
Shoppers expect quick and secure payment options. Many stores now accept contactless payments, making checkout…
In the world of different programming languages and many development tools, outsourcing have emerged as…