List
- Lists are used to store multiple items in a single variable.
- Lists are created using square brackets.
- List is a built-in data structure used to store an ordered collection of items. They are dynamic, resizable and capable of storing multiple data types.
Ex:
a = [1, 2, 3]
print(a)
b = ["apple", "banana"]
print(b)
List Items - Data Types
- List items can be of any data type.
- A list with strings, integers and boolean values.
Ex:
list1 = ["apple", 1 , False]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list1)
print(list2)
print(list3)
List Operations:
There are several kinds of list operations,they are:
- Add()
- Delete()
- Reorder()
Add():
- append() → Adds an item at the end.
- insert() → Adds an item at a specific position.
- extend() → Adds multiple items from another list.
Delete():
- pop() → Removes item by index (default: last item).
- remove() → Removes item by value.
- clear() → Removes all items.
Reorder():
- sort() → Sorts items in ascending order.
- reverse() → Reverses the order of items.
Practice problems:
- Input: [56, 54, 100, 35, 83, 81, 100, 66, 93, 81, 79, 67, 100, 50, 74, 59, 100, 61, 37, 60]
- Given math scores, find how many scored centum: 100
- Given scores, grade each score: A > 90, B > 80, C > 60, others D
- Given scores, count students for each grade
input = [56, 54, 100, 35, 83, 81, 100, 66, 93, 81, 79, 67, 100, 50, 74, 59, 100, 61, 37, 60]
count = 0
for i in input:
if i == 100:
count = count + 1
print("Centum scored: ", count)
grade_A = 0
grade_B = 0
grade_C = 0
grade_D = 0
for i in input:
if i > 90:
grade_A = grade_A + 1
elif i > 80:
grade_B = grade_B + 1
elif i > 60:
grade_C = grade_C + 1
else:
grade_D = grade_D + 1
print("A_Grade: ", grade_A)
print("B_Grade: ", grade_B)
print("C_Grade: ", grade_C)
print("D_Grade: ", grade_D)
- Given numbers, reverse numbers [1, 2, 3] -> [3, 2, 1]
num = [1, 2, 3]
num.reverse()
print("Reversed numbers: ", num)
- Given numbers, rotate them in place N times [1, 2, 3, 4, 5] -> [4, 5, 1, 2, 3]
nums = [1, 2, 3, 4, 5]
N = 2
for i in range(N):
last = nums.pop()
nums.insert(0, last)
print("Rotated list:", nums)
- Given numbers, double them in place [1, 2, 3, 4, 5] -> [2, 4, 6, 8, 10]
num = [1, 2, 3, 4, 5]
for i in range(len(num)):
num[i] = num[i] * 2
print("Doubled numbers: ", num)
- Sort given numbers
num = [1, 2, 3, 4, 5]
num.sort()
print("Sorted numbers: ", num)
- Sum of given numbers
num = [1, 2, 3, 4, 5]
total = 0
for i in num:
total = total + i
print("Sum of numbers: ", total)
- Find even, odd
input = [56, 54, 100, 35, 83, 81, 100]
for i in input:
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
- Multiply by 2
num = [1, 2, 3, 4, 5]
for i in range(len(num)):
num[i] = num[i] * 2
print("Multiplied by 2: ", num)
- Compare two lists for equality
list1 = [1, 2, 3]
list2 = [4, 5, 6]
if list1 == list2:
print("Lists are equal")
else:
print("Lists are not equal")
Top comments (0)