- Creating a List: To create a list, you can use square brackets
[]
and separate the elements with commas.pythonCopy codemy_list = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "cherry"] mixed_list = [1, "hello", 3.14, True] empty_list = []
- Accessing Elements: You can access elements in a list by using their index, starting from 0 for the first element.pythonCopy code
first_element = my_list[0] second_element = fruits[1]
- Slicing: You can extract a subset of elements from a list using slicing.pythonCopy code
some_elements = my_list[1:4] # Gets elements at index 1, 2, and 3
- Modifying Lists: Lists are mutable, so you can change their contents.
- Adding elements:
append()
: Add an element to the end of the list.insert()
: Insert an element at a specific index.
fruits.append("orange") fruits.insert(1, "grape")
- Removing elements:
remove()
: Remove the first occurrence of a specific value.pop()
: Remove an element by index and return it.
fruits.remove("banana") popped_element = fruits.pop(2)
- Adding elements:
- List Length: You can find the number of elements in a list using the
len()
function.pythonCopy codenum_elements = len(fruits)
- List Concatenation: You can concatenate two or more lists using the
+
operator.pythonCopy codecombined_list = fruits + ["kiwi", "melon"]
- Sorting: You can sort a list using the
sort()
method (in-place) or thesorted()
function (creates a new sorted list).pythonCopy codefruits.sort() # Sorts the list in-place sorted_fruits = sorted(fruits) # Creates a new sorted list
- List Comprehensions: List comprehensions are a concise way to create lists based on existing lists.pythonCopy code
squares = [x ** 2 for x in range(1, 6)] # Creates a list of squares from 1 to 5
These are some of the basic operations you can perform with Python lists. Lists are a fundamental data structure and are widely used in Python programming for various tasks.