Lesson 4 of 15
Lists
Lists
A Python list is an ordered, mutable sequence of any type. Lists are created with square brackets.
Creating and Accessing
nums = [3, 1, 4, 1, 5]
nums[0] # 3
nums[-1] # 5
nums[1:3] # [1, 4]
Mutating Lists
nums.append(9) # add to end
nums.insert(0, 0) # insert at index
nums.pop() # remove last
nums.pop(0) # remove at index
nums.remove(1) # remove first occurrence of value
nums.sort() # sort in-place
nums.reverse() # reverse in-place
Useful Built-ins
len([1, 2, 3]) # 3
sum([1, 2, 3]) # 6
min([3, 1, 2]) # 1
max([3, 1, 2]) # 3
sorted([3, 1, 2]) # [1, 2, 3] (returns new list)
list(range(5)) # [0, 1, 2, 3, 4]
Checking Membership
3 in [1, 2, 3] # True
4 in [1, 2, 3] # False
Your Task
Implement two_sum(nums, target) that:
- Returns
Trueif any two distinct elements innumssum totarget - Returns
Falseotherwise
Hint: use a set to track which numbers you've seen. A set is an unordered collection of unique elements — created with set() — that supports O(1) lookups via in, and .add() to insert elements. (Sets also support operations like | for union and & for intersection.)
Pyodide loading...
Loading...
Click "Run" to execute your code.