Level 1: Basic List Creation and Access
# Creating a list
fruits = ['apple', 'banana', 'cherry']
# Accessing elements
print(fruits[0])
# Adding an element
fruits.append('date')
print(fruits)
# Removing an element
fruits.remove('banana')
print(fruits)
#clcoding.com
apple
['apple', 'banana', 'cherry', 'date']
['apple', 'cherry', 'date']
Level 2: List Slicing and Iteration
# Slicing a list
print(fruits[1:3]) # Output: ['cherry', 'date']
# Iterating over a list
for fruit in fruits:
print(fruit)
#clcoding.com
['cherry', 'date']
apple
cherry
date
Level 3: List Comprehensions
List comprehensions offer a concise way to create lists. They can replace loops for generating list elements.
# Creating a list of squares using list comprehension
squares = [x**2 for x in range(10)]
print(squares)
#clcoding.com
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Level 4: Nested Lists and Multidimensional Arrays
# Creating a nested list (2D array)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements in a nested list
print(matrix[1][2]) # Output: 6
# Iterating over a nested list
for row in matrix:
for elem in row:
print(elem, end=' ')
print()
#clcoding.com
6
1 2 3
4 5 6
7 8 9
Level 5: Advanced List Operations
# List comprehension with conditionals
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
# Using higher-order functions: map, filter, and reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Map: Apply a function to all items in the list
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) #
# Filter: Filter items based on a condition
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
#clcoding.com
[0, 4, 16, 36, 64]
[2, 4, 6, 8, 10]
[2, 4]
# Reduce: Reduce the list to a single value
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers)
# List references and copying
list1 = [1, 2, 3]
list2 = list1 # list2 is a reference to list1
list2.append(4)
print(list1)
# Proper copying
list3 = list1.copy()
list3.append(5)
print(list1)
print(list3)
#clcoding.com
15
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
0 Comments:
Post a Comment