Jul 11, 2024
my_list = [1, 2, 3, 'apple']
[]
my_list[0] # First element
my_list[-1] # Last element
my_list[start:stop]
my_list[1] = 'pear' # Modify second element
squares = [x*x for x in range(10)]
my_tuple = (1, 2, 3, 'apple')
()
my_tuple[0] # First element
my_tuple[-1] # Last element
my_set = {1, 2, 3, 'apple'}
or using the set function:
my_set = set([1, 2, 3, 'apple'])
{}
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
{}
my_dict['name'] # John
my_dict['age'] = 31
my_dict['email'] = 'john@example.com'
my_dict.pop('age') # Removes 'age' key
None
if key does not existfor key in my_dict:
print(key, my_dict[key])
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(key, value)
{x: x*x for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
def sum_list(lst):
total = 0
for num in lst:
total += num
return total
my_list = [3, 1, 4, 1, 5, 9, 2]
max_val = max(my_list)
min_val = min(my_list)
print(f"Max: {max_val}, Min: {min_val}")
def unique_elements(lst):
return list(set(lst))
def count_occurrences(lst, val):
return lst.count(val)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict['age'] = 31 # Update value
for key, value in my_dict.items():
print(f"{key}: {value}")