Lists in Python are versatile, ordered, and mutable sequences of items.
They are defined using
square brackets [], with elements separated by commas. Lists can contain items of different
data types, including integers, floats, strings, and even other lists.
Here's how to work with lists in Python:
Creating Lists
# Empty list
my_list = []
# List with initial values
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", 3.14, True]
Accessing Elements
List elements are accessed using their index, starting from 0 for the first element.
print(numbers[0]) # Output: 1
print(fruits[2]) # Output: cherry
Negative indexing can be used to access elements from the end of the list.
print(numbers[-1]) # Output: 5 (last element)
Modifying Lists
Lists are mutable, meaning their elements can be changed after creation.
# Changing an element
numbers[1] = 10
print(numbers) # Output: [1, 10, 3, 4, 5]
# Adding elements
[Link](6) # Adds 6 to the end
print(numbers) # Output: [1, 10, 3, 4, 5, 6]
[Link](2, 20) # Inserts 20 at index 2
print(numbers) # Output: [1, 10, 20, 3, 4, 5, 6]
# Removing elements
[Link](10) # Removes the first occurrence of 10
print(numbers) # Output: [1, 20, 3, 4, 5, 6]
popped_element = [Link](1) # Removes and returns the element
at index 1
print(numbers) # Output: [1, 3, 4, 5, 6]
print(popped_element) # Output: 20
# List Concatenation and Repetition
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
repeated_list = list1 * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Slicing Lists
Slicing extracts a portion of a list.
sub_list = numbers[1:4] # Elements from index 1 to 3 (exclusive of
4)
print(sub_list) # Output: [3, 4, 5]
sub_list_start = numbers[2:] # Elements from index 2 to the end
print(sub_list_start) # Output: [4, 5, 6]
sub_list_end = numbers[:4] # Elements from the beginning to index 3
(exclusive of 4)
print(sub_list_end) # Output: [1, 3, 4, 5]
Other Operations
# Length of a list
print(len(numbers)) # Output: 5
# Checking if an element exists
print(3 in numbers) # Output: True
# Iterating through a list
for number in numbers:
print(number)
Generative AI is experimental.
[-] [Link]
-tasks-398111