Friday 26 July 2024

Python List examples

Here are some basic and common examples of Python list operations:



### Creating a List

```python

# Creating a list of numbers

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

 

# Creating a list of strings

fruits = ["apple", "banana", "cherry"]

 

# Creating a mixed list

mixed_list = [1, "hello", 3.14, True]

```

 

### Accessing Elements

```python

# Accessing elements by index

first_number = numbers[0]  # 1

second_fruit = fruits[1]  # "banana"

 

# Accessing the last element

last_number = numbers[-1]  # 5

```

 

### Slicing a List

```python

# Getting a sublist

sublist = numbers[1:4]  # [2, 3, 4]

 

# Slicing with step

step_slice = numbers[::2]  # [1, 3, 5]

```

 

### Modifying Elements

```python

# Changing an element by index

numbers[2] = 10  # [1, 2, 10, 4, 5]

 

# Appending an element to the list

numbers.append(6)  # [1, 2, 10, 4, 5, 6]

 

# Inserting an element at a specific position

numbers.insert(1, 20)  # [1, 20, 2, 10, 4, 5, 6]

```

 

### Removing Elements

```python

# Removing an element by value

numbers. Remove(10)  # [1, 20, 2, 4, 5, 6]

 

# Removing an element by index

del numbers[1]  # [1, 2, 4, 5, 6]

 

# Popping the last element

last_element = numbers.pop()  # 6, numbers: [1, 2, 4, 5]

```

 

### List Operations

```python

# Concatenating lists

new_list = numbers + [7, 8, 9]  # [1, 2, 4, 5, 7, 8, 9]

 

# Repeating lists

repeated_list = fruits * 2  # ["apple", "banana", "cherry", "apple", "banana", "cherry"]

```

 

### List Comprehensions

```python

# Creating a list with a comprehension

squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

 

# Filtering with a comprehension

even_numbers = [x for x in numbers if x % 2 == 0]  # [2, 4]

```

 

### List Functions and Methods

```python

# Finding the length of a list

length = len(numbers)  # 5

 

# Finding the maximum and minimum values

max_value = max(numbers)  # 5

min_value = min(numbers)  # 1

 

# Sorting a list

sorted_numbers = sorted(numbers)  # [1, 2, 4, 5]

numbers.sort()  # In-place sorting, numbers: [1, 2, 4, 5]

 

# Reversing a list

numbers.reverse()  # In-place reverse, numbers: [5, 4, 2, 1]

reversed_numbers = numbers[::-1]  # [1, 2, 4, 5]

```

 

These examples cover a wide range of common operations that can be performed on lists in Python.

 

TCCI Computer classes provide the best training in online computer courses through different learning methods/media located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.

For More Information:                                    

Call us @ +91 98256 18292

Visit us @ http://tccicomputercoaching.com/

No comments:

Post a Comment