Wednesday, 1 March 2023

Operation on List in Python

 Here are some of the most common operations you can perform on a list in Python:

  1. Creating a list: To create a new list, simply enclose a comma-separated sequence of values in square brackets [].

Example:

css
my_list = [1, 2, 3, 4, 5]
  1. Accessing elements: To access an element in a list, use its index within square brackets. Python uses zero-based indexing, so the first element is at index 0.

Example:

python
print(my_list[0]) # Output: 1
  1. Slicing: To retrieve a sublist of a list, use slicing notation with the start and end index separated by a colon. The slice includes the element at the start index and excludes the element at the end index.

Example:

python
print(my_list[1:3]) # Output: [2, 3]
  1. Modifying elements: You can change the value of an element in a list by assigning a new value to its index.

Example:

scss
my_list[3] = 10 print(my_list) # Output: [1, 2, 3, 10, 5]
  1. Adding elements: To add an element to the end of a list, use the append() method. To insert an element at a specific index, use the insert() method.

Example:

scss
my_list.append(6) print(my_list) # Output: [1, 2, 3, 10, 5, 6] my_list.insert(2, 4) print(my_list) # Output: [1, 2, 4, 3, 10, 5, 6]
  1. Removing elements: To remove an element from a list, use the remove() method if you know the value of the element, or the del statement if you know the index.

Example:

python
my_list.remove(4) print(my_list) # Output: [1, 2, 3, 10, 5, 6] del my_list[1] print(my_list) # Output: [1, 3, 10, 5, 6]
  1. Sorting: To sort the elements of a list, use the sort() method.

Example:

scss
my_list.sort() print(my_list) # Output: [1, 3, 5, 6, 10]
  1. Reversing: To reverse the order of the elements in a list, use the reverse() method.

Example:

perl
my_list.reverse() print(my_list) # Output: [10, 6, 5, 3, 1]
  1. Length: To get the number of elements in a list, use the len() function.

Example:

python
print(len(my_list)) # Output: 5
  1. Concatenation: To concatenate two or more lists, use the + operator.

Example:

scss
my_list2 = [7, 8, 9] print(my_list + my_list2) # Output: [1, 3, 5, 6, 10, 7, 8, 9]
  1. Membership: To check if an element is in a list, use the in operator.

Example:

python
print(5 in my_list) # Output: True print(15 in my_list) # Output: False

No comments:

Post a Comment

Program For String

 # This program demonstrates various string operations # Define a string variable my_string = "Hello, World!" # Print the string p...