Index
Lists in Python
List Methods in Python
Tuples in Python
1. Lists in Python
Definition:
A list in Python is an ordered collection of elements that can contain items of different data types. Lists are mutable, meaning that the elements within a list can be changed or modified.
Syntax:
list_name = [element1, element2, element3, ...]
Examples:
Basic Example:
fruits = ['apple', 'banana', 'cherry']
print(fruits)
Output:['apple', 'banana', 'cherry']
Advanced Example:
mixed_list = [1, 'hello', [2, 3], {'key': 'value'}] mixed_list[2][1] = 'world' print(mixed_list)
Output:[1, 'hello', [2, 'world'], {'key': 'value'}]
2. List Methods in Python
Definition:
List methods are functions available to lists in Python, allowing various operations like adding, removing, and manipulating elements.
Common List Methods:
append(): Adds an element to the end of the list.
extend(): Adds all elements of an iterable to the end of the list.
insert(): Inserts an element at a specified position.
remove(): Removes the first occurrence of an element.
pop(): Removes an element at a specified position or the last element if no position is provided.
Syntax:
list_name.method(arguments)
Examples:
Basic Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
Output:[1, 2, 3, 4]
Advanced Example:
numbers = [10, 20, 30, 40, 50]
numbers.insert(2, 25)
numbers.remove(50)
print(numbers)
Output:[10, 20, 25, 30, 40]
3. Tuples in Python
Definition:
A tuple in Python is an ordered collection of elements similar to a list, but unlike lists, tuples are immutable. Once created, the elements within a tuple cannot be changed.
Syntax:
tuple_name = (element1, element2, element3, ...)
Examples:
Basic Example:
coordinates = (10.5, 20.3)
print(coordinates)
Output:(10.5, 20.3)
Advanced Example:
nested_tuple = (1, (2, 3), [4, 5])
print(nested_tuple[1][1])
Output:3
This issue of FM University provides you with the foundational concepts of Python's Lists and Tuples, equipping you to build more complex programs. Stay tuned for more in-depth Python insights!
- Vishal Rajput