Python Lists Tutorial
1. What is a List?
A list is a collection of items that can be of different types. Lists are ordered, mutable (changeable), and allow duplicate values.
2. Creating a List
You can create a list by placing items inside square brackets [], separated by commas.
python1# Creating an empty list 2my_list = [] 3 4# Creating a list with integers 5numbers = [1, 2, 3, 4, 5] 6 7# Creating a list with mixed data types 8mixed_list = [1, "Hello", 3.14, True] 9 10# Creating a list of lists (nested list) 11nested_list = [[1, 2, 3], ["a", "b", "c"]]
3. Accessing List Elements
You can access elements in a list using their index. Remember that Python uses zero-based indexing.
python1# Accessing elements 2print(numbers[0]) # Output: 1 3print(mixed_list[1]) # Output: Hello 4print(nested_list[1][0]) # Output: a
4. Modifying Lists
Lists are mutable, meaning you can change their content.
python1# Changing an element 2numbers[0] = 10 3print(numbers) # Output: [10, 2, 3, 4, 5] 4 5# Adding elements 6numbers.append(6) # Adds 6 to the end of the list 7print(numbers) # Output: [10, 2, 3, 4, 5, 6] 8 9# Inserting elements 10numbers.insert(1, 15) # Inserts 15 at index 1 11print(numbers) # Output: [10, 15, 2, 3, 4, 5, 6] 12 13# Removing elements 14numbers.remove(15) # Removes the first occurrence of 15 15print(numbers) # Output: [10, 2, 3, 4, 5, 6] 16 17# Popping elements 18popped_element = numbers.pop() # Removes and returns the last element 19print(popped_element) # Output: 6 20print(numbers) # Output: [10, 2, 3, 4, 5]
5. List Methods
Python provides several built-in methods to manipulate lists.
append(): Adds an item to the end of the list.extend(): Adds elements from another list to the end of the current list.insert(): Inserts an item at a specified index.remove(): Removes the first occurrence of a specified value.pop(): Removes and returns an item at a specified index (default is the last item).clear(): Removes all items from the list.index(): Returns the index of the first occurrence of a specified value.count(): Returns the number of occurrences of a specified value.sort(): Sorts the list in ascending order.reverse(): Reverses the order of the list.
python1# Using some list methods 2numbers.extend([7, 8, 9]) # Extends the list with another list 3print(numbers) # Output: [10, 2, 3, 4, 5, 7, 8, 9] 4 5numbers.sort() # Sorts the list 6print(numbers) # Output: [2, 3, 4, 5, 7, 8, 10] 7 8numbers.reverse() # Reverses the list 9print(numbers) # Output: [10, 8, 7, 5, 4, 3, 2]
6. List Comprehensions
List comprehensions provide a concise way to create lists. They consist of brackets containing an expression followed by a for clause.
python1# Creating a list of squares using list comprehension 2squares = [x**2 for x in range(10)] 3print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 4 5# Filtering with list comprehension 6even_squares = [x**2 for x in range(10) if x % 2 == 0] 7print(even_squares) # Output: [0, 4, 16,
No comments:
Post a Comment