Python Lists: A Comprehensive Guide with Examples of List Manipulation

codepythonic
0

Python Lists: A Comprehensive Guide with Examples of List Manipulation


Python lists along with code examples for each method:


**Python Lists:**


- Lists are a collection of items that are ordered and mutable, meaning you can change, add, or remove elements.


**Creating a List:**

```python

# Empty list

empty_list = []


# List with elements

numbers = [1, 2, 3, 4, 5]

fruits = ['apple', 'banana', 'orange']

```


**Accessing Elements:**

```python

numbers = [1, 2, 3, 4, 5]

print(numbers[0])  # Output: 1

print(numbers[2])  # Output: 3

print(numbers[-1]) # Output: 5 (last element)

```


**Slicing Lists:**

```python

numbers = [1, 2, 3, 4, 5]

print(numbers[1:4])    # Output: [2, 3, 4]

print(numbers[:3])     # Output: [1, 2, 3]

print(numbers[2:])     # Output: [3, 4, 5]

print(numbers[::2])    # Output: [1, 3, 5] (every second element)

```


**List Length:**

```python

numbers = [1, 2, 3, 4, 5]

length = len(numbers)

print(length)  # Output: 5

```


**Adding Elements:**

```python

fruits = ['apple', 'banana', 'orange']

fruits.append('grape')    # Add 'grape' at the end

fruits.insert(1, 'kiwi')  # Insert 'kiwi' at index 1

print(fruits)             # Output: ['apple', 'kiwi', 'banana', 'orange', 'grape']

```


**Removing Elements:**

```python

fruits = ['apple', 'banana', 'orange', 'grape']

fruits.remove('banana')      # Remove 'banana'

popped_fruit = fruits.pop()  # Remove the last element and get its value

print(fruits)               # Output: ['apple', 'orange']

print(popped_fruit)         # Output: 'grape'

```


**List Comprehension:**

```python

# Create a new list based on existing list with some modification

numbers = [1, 2, 3, 4, 5]

squared_numbers = [n**2 for n in numbers]

print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

```


**Sorting a List:**

```python

numbers = [3, 1, 4, 2, 5]

numbers.sort()          # Sort the list in ascending order

print(numbers)          # Output: [1, 2, 3, 4, 5]


fruits = ['banana', 'orange', 'apple']

sorted_fruits = sorted(fruits)  # Create a new sorted list

print(sorted_fruits)           # Output: ['apple', 'banana', 'orange']

```


**Checking Element Existence:**

```python

numbers = [1, 2, 3, 4, 5]

print(3 in numbers)     # Output: True

print(6 not in numbers) # Output: True

```


**Clearing a List:**

```python

numbers = [1, 2, 3, 4, 5]

numbers.clear()  # Remove all elements from the list

print(numbers)   # Output: []

```


Lists are versatile and widely used in Python for storing collections of data. I hope these examples help you understand Python lists better for your tutorial blog! Happy coding!

Post a Comment

0Comments

Post a Comment (0)