Lists in Python Programming Language

Lists in Python Programming Language

Lists in Python

Introduction to Python Lists:

What is a List?

# List of integers
numbers = [10, 0, 5, -1, -7, 90]

# List of strings
strings = ['data', 'google', 'journey', 'computer']

# Mixed list containing different data types
mix_list = [46, 'software', 'S', True, 2.59]
  1. numbers: This variable holds multiple integer values in an organized way. The list can contain both positive and negative integers.
  2. strings: The variable holds a list of string values, and we can add, delete, or rearrange these values as needed.
  3. mix_list: This variable holds a list of mixed data types, including integers, floats, strings, characters, and boolean values. This demonstrates that a list can store different types of data at the same time.

Indexing in Lists

  • The value 10 is at index 0
  • The value 0 is at index 1
  • The value 5 is at index 2
  • The value -1 is at index 3
  • The value -7 is at index 4
  • The value 90 is at index 5

Accessing Specific Values by Index

number2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(number2)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Accessing the value at the 3rd index
print(number2[3])
# Output: 4

Slicing Lists

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

Index + Length + Skip:

print(number2[1:6:2])
# Output: [2, 4, 6]

Manipulating Lists
Sorting a List:

numbers = [10, 0, 5, -1, -7, 90]
numbers.sort()

print(numbers)
# Output: [-7, -1, 0, 5, 10, 90]

Reversing a List:

numbers.reverse()

print(numbers)
# Output: [90, 10, 5, 0, -1, -7]

Finding Minimum and Maximum Values:

print(min(numbers))  # Output: -7
print(max(numbers))  # Output: 90

Adding a New Element:

numbers.append(45)

print(numbers)
# Output: [10, 0, 5, -1, -7, 90, 45]

Inserting an Element at a Specific Index:

numbers.insert(2, 61)

print(numbers)
# Output: [10, 0, 61, 5, -1, -7, 90]

Extending a List:

numbers.extend([21, 32, 62])

print(numbers)
# Output: [10, 0, 61, 5, -1, -7, 90, 21, 32, 62]

Replacing Values in a List
Replacing a Value at a Specific Index:

numbers[1] = 45

print(numbers)
# Output: [10, 45, 61, 5, -1, -7, 90, 21, 32, 62]

Replacing Multiple Values:

numbers[1:4] = [45, 46, 47]

print(numbers)
# Output: [10, 45, 46, 47, -7, 90]

Removing Elements from a List
Removing a Specific Value:

numbers.remove(10)

print(numbers)
# Output: [45, 46, 47, -7, 90]

Removing an Element by Index:

numbers.pop(2)

print(numbers)
# Output: [45, 46, -7, 90]

Conclusion

administrator

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *