List
- A
List
is a dynamic array in Python, allowing you to store multiple different values, and elements can be changed after initialization. - To declare a
List
, use square brackets[]
.
Example:
# Declare a List containing integers
numbers = [1, 2, 3, 4, 5]
# Access and print elements in the List
print(numbers[0]) # Output: 1
print(numbers[2]) # Output: 3
# Modify the value of an element in the List
numbers[1] = 10
print(numbers) # Output: [1, 10, 3, 4, 5]
Tuple
- A
Tuple
is an immutable data structure in Python, often used to protect data from being changed after initialization. - To declare a
Tuple
, use parentheses()
.
Example:
# Declare a Tuple containing information of a student
student_info = ('John', 25, 'Male', 'New York')
# Access and print elements in the Tuple
print(student_info[0]) # Output: John
print(student_info[2]) # Output: Male
Set
- A
Set
is a data structure that does not contain duplicate elements and has no order. - To declare a
Set
, use curly braces{}
or theset()
function.
Example:
# Declare a Set containing colors
colors = {'red', 'green', 'blue', 'red', 'yellow'}
# Print the Set to check duplicate elements are removed
print(colors) # Output: {'red', 'green', 'blue', 'yellow'}
Dictionary
- A
Dictionary
is an unordered data structure that stores information in key-value pairs. - To declare a
Dictionary
, use curly braces{}
and separate each key-value pair with a colon:
.
Example:
# Declare a Dictionary containing information of a person
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# Access and print values from the Dictionary
print(person['name']) # Output: John
print(person['age']) # Output: 30
# Modify the value of a key in the Dictionary
person['city'] = 'Los Angeles'
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'Los Angeles'}
These data structures allow programmers to manipulate and process data flexibly in Python, suitable for various programming scenarios and purposes.