Python Lists
⏱ Estimated reading time: 2 min
Python Lists
A list in Python is an ordered, changeable collection of items. Lists can contain elements of different data types, including numbers, strings, and other lists.
Creating a list:
Example:
my_list = [1, 2, 3, 4]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.5]
Accessing elements:
Use the index to access items. Indexing starts from 0.
Example:
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
Slicing a list:
Get a sublist using a range of indexes.
Example:
print(fruits[0:2]) # ['apple', 'banana']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[1:]) # ['banana', 'cherry']
Changing elements:
Lists are mutable, so you can change items.
Example:
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
Adding elements:
-
append(): adds an item at the end
Example:
fruits.append("orange") -
insert(): adds an item at a specific position
Example:
fruits.insert(1, "kiwi")
Removing elements:
-
remove(): removes first matching value
Example:
fruits.remove("apple") -
pop(): removes item at index (default last)
Example:
fruits.pop() -
del: removes item or whole list
Example:
del fruits[0]
del fruits
List length:
Use len() to get the number of items.
Example:
len(fruits)
Iterating through a list:
Use a for loop to access each item.
Example:
for fruit in fruits:
print(fruit)
Checking existence of an element:
Use in to check if an item exists.
Example:
if "apple" in fruits:
print("Found")
List methods:
-
sort(): sorts the list in ascending order
-
reverse(): reverses the list
-
copy(): creates a copy of the list
-
clear(): removes all items
-
count(): returns number of occurrences of a value
-
extend(): adds elements from another list
Example:
numbers = [3, 1, 4, 2]
numbers.sort()
numbers.reverse()
Nested lists:
Lists can contain other lists.
Example:
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[0][1]) # 2
Register Now
Share this Post
← Back to Tutorials