Python Lists are one of the most versatile and widely used data structures in Python programming. Lists are mutable, ordered collections that allow duplicate elements. They are dynamic, meaning you can add, remove, and modify elements easily, making them essential for handling grouped data in Python.
A list in Python is defined by enclosing comma-separated values within square brackets []. Each item in a list can be of a different data type including integers, floats, strings, or even other lists.
# Creating a list my_list = [1, 2, 3, "apple", 4.5] # Accessing elements print(my_list[0]) # Output: 1
# Empty list empty = [] # List with elements fruits = ["apple", "banana", "cherry"] # Using list constructor numbers = list((1, 2, 3, 4)) # List from string chars = list("hello")
names = ["Alice", "Bob", "Charlie"] print(names[1]) # Output: Bob
print(names[-1]) # Output: Charlie
print(names[0:2]) # Output: ['Alice', 'Bob']
names[0] = "Alex" print(names) # Output: ['Alex', 'Bob', 'Charlie']
names.append("Diana") names.insert(1, "Brian")
names.remove("Bob") del names[2]
Method | Description |
---|---|
append() | Adds an element at the end |
insert() | Inserts an element at a specific position |
remove() | Removes the first occurrence of an element |
pop() | Removes the element at the given index |
sort() | Sorts the list in ascending order |
reverse() | Reverses the list order |
for fruit in fruits: print(fruit)
i = 0 while i < len(fruits): print(fruits[i]) i += 1
List comprehensions provide a concise way to create lists using a single line of code.
squares = [x**2 for x in range(10)] print(squares)
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[1][2]) # Output: 6
original = [1, 2, 3] copy_list = original[:]
copy_list = original.copy()
Python Lists are indispensable tools for any Python programmer. With their dynamic nature, ease of use, and vast method support, they simplify working with sequences of data. From simple storage to advanced transformations, mastering Python Lists enables cleaner and more efficient code development.
Copyrights © 2024 letsupdateskills All rights reserved