list_python
list_python
1. Introduction to Lists
2. Creating Lists
List indices work similarly to string indices. Use the subscript operator [ ] to access
elements.
4. List Comprehension
2. list_1 = [1,2,3,4,5,6,7,8,9,10]
selected_list = [x for x in list_1 if x % 2 == 0]
5. List Operations
list_a = [1, 2, 3]
list_b = ["a","b",77]
combined_list = list_a + list_b
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
list_a = [1, 2, 3]
repeated_list = list_a * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Relational operators (like >, <) compare lists lexicographically (i.e., element by
element).
list_x = [1, 2, 3]
list_y = [1, 2, 4]
print(list_x < list_y) # Output: True, because 3 < 4 in the first
# non-matching pair
list_a = [2, 3, 5]
list_b = [2, 3, 5, 7]
print(list_a < list_b) # Output: True, because list_a is shorter and
# identical in elements up to its length
list_c = [3, 4, 5]
list_d = [3, 2, 5]
print(list_c > list_d) # Output: True, because 4 > 2 in the second
# position
list_c = [3, 4, 5]
list_d = [3, 4, 5]
print(list_c == list_d) # True
6. Membership Operators
List_1 = [2, 4, 6]
print(2 in list_1) # Output: True
7. List Slices
my_list = [1,2,3,"a","b","c"]
sublist = my_list[1:3]
8. List Mutability
Inserting elements: The slice operator can insert elements at a specified position.
prime = [2, 3, 5, 7]
prime[4:4] = [11] #insert „11‟ at index 4
my_list = [“a”,1,3,45,56,”x”]
del my_list[2] # ['a', 1, 45, 56, 'x']
char_list = list("hello")
Example 1:
a b c
1 0 1 2
7
0 1 2
Accessing elements:
list[0] = 1
list[1][0] = a
list[1][1] = b
list[1][2] = c
list[2] = 7
Example 2:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Aliasing: Assigning a list to another variable creates a reference to the same list.
alias_list = original_list
cloned_list = original_list[:]