Level 1: Basic List Creation
# Creating a simple list
my_list = [1, 2, 3, 4, 5]
print(my_list)
#clcoding.com
[1, 2, 3, 4, 5]
Level 2: Accessing List Elements
# Accessing elements by index
my_list = [1, 2, 3, 4, 5]
first_element = my_list[0]
last_element = my_list[-1]
print( "First:", first_element, "Last:", last_element)
#clcoding.com
First: 1 Last: 5
Level 3: List Slicing
# Slicing a list
my_list = [1, 2, 3, 4, 5]
sub_list = my_list[1:4]
print(sub_list)
#clcoding.com
[2, 3, 4]
Level 4: Adding Elements to a List
# Appending and extending a list
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
my_list.extend([7, 8])
print(my_list)
#clcoding.com
[1, 2, 3, 4, 5, 6, 7, 8]
Level 5: Removing Elements from a List
# Removing elements
my_list = [1, 2, 3, 4, 5]
my_list.remove(2)
popped_element = my_list.pop()
print(my_list)
print(popped_element)
#clcoding.com
[1, 3, 4]
5
Level 6: List Comprehensions
# Using list comprehensions
my_list = [1, 2, 3, 4, 5]
squared_list = [x**2 for x in my_list]
print(squared_list)
#clcoding.com
[1, 4, 9, 16, 25]
Level 7: Nested Lists
# Creating and accessing nested lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
element = nested_list[1][2]
print(nested_list, element)
#clcoding.com
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 6
Level 8: Using List Functions and Methods
# Using built-in functions and methods
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
sorted_list = sorted(my_list)
my_list.sort(reverse=True)
print(length, sorted_list, my_list)
#clcoding.com
5 [1, 2, 3, 4, 5] [5, 4, 3, 2, 1]
Level 9: List Iteration
# Iterating over a list
for element in my_list:
print(element)
5
4
3
2
1
Level 10: Advanced List Operations
# Using advanced operations like map, filter, and reduce
my_list = [1, 2, 3, 4, 5]
from functools import reduce
# Map: applying a function to each element
doubled_list = list(map(lambda x: x * 2, my_list))
print(doubled_list)
# Filter: filtering elements based on a condition
even_list = list(filter(lambda x: x % 2 == 0, my_list))
print(even_list)
# Reduce: reducing the list to a single value
sum_of_elements = reduce(lambda x, y: x + y, my_list)
print(sum_of_elements)
#clcoding.com
[2, 4, 6, 8, 10]
[2, 4]
15
0 Comments:
Post a Comment