Python Basics: Functions, Lists, Tuples, Sets, and Dictionaries
1. Functions
Syntax:
def function_name(parameters):
# code block
return result
Explanation:
- Functions are blocks of reusable code to perform a specific task.
- Defined using the 'def' keyword followed by the function name and parentheses.
Example:
def add(a, b):
return a + b
print(add(2, 3)) # Output: 5
2. Lists
Syntax:
my_list = [item1, item2, item3]
Explanation:
- Lists are ordered, mutable collections of items.
- Items can be of mixed data types.
Example:
fruits = ['apple', 'banana', 'cherry']
Common List Methods:
append()
Explanation: Adds an item to the end of the list.
Example:
[Link]('orange')
extend()
Explanation: Adds multiple items to the list.
Example:
[Link](['grape', 'melon'])
insert()
Explanation: Inserts an item at a given position.
Example:
[Link](1, 'kiwi')
remove()
Explanation: Removes first occurrence of a value.
Example:
[Link]('banana')
pop()
Explanation: Removes and returns item at a given index.
Example:
[Link](0)
3. Tuples
Syntax:
my_tuple = (item1, item2, item3)
Explanation:
- Tuples are ordered and immutable collections.
- Useful when data should not be changed.
Example:
coordinates = (10, 20)
Common Tuple Methods:
count()
Explanation: Returns the number of times a value appears.
Example:
[Link](10)
index()
Explanation: Returns the index of the first occurrence of a value.
Example:
[Link](20)
len()
Explanation: Returns the number of items in the tuple.
Example:
len(coordinates)
max()
Explanation: Returns the largest item.
Example:
max(coordinates)
min()
Explanation: Returns the smallest item.
Example:
min(coordinates)
4. Sets
Syntax:
my_set = {item1, item2, item3}
Explanation:
- Sets are unordered collections of unique items.
- Useful for removing duplicates and performing set operations.
Example:
colors = {'red', 'green', 'blue'}
Common Set Methods:
add()
Explanation: Adds a single element to the set.
Example:
[Link]('yellow')
update()
Explanation: Adds multiple elements to the set.
Example:
[Link](['black', 'white'])
remove()
Explanation: Removes an element (raises error if not found).
Example:
[Link]('green')
discard()
Explanation: Removes an element (does nothing if not found).
Example:
[Link]('purple')
clear()
Explanation: Removes all elements from the set.
Example:
[Link]()
5. Dictionaries
Syntax:
my_dict = {key1: value1, key2: value2}
Explanation:
- Dictionaries are unordered collections of key-value pairs.
- Keys must be unique and immutable.
Example:
student = {'name': 'Alice', 'age': 20}
Common Dictionary Methods:
get()
Explanation: Returns value for specified key.
Example:
[Link]('name')
keys()
Explanation: Returns a view of dictionary keys.
Example:
[Link]()
values()
Explanation: Returns a view of dictionary values.
Example:
[Link]()
items()
Explanation: Returns a view of key-value pairs.
Example:
[Link]()
update()
Explanation: Updates the dictionary with elements from another dict.
Example:
[Link]({'grade': 'A'})