Skip to content

python list

  1. Creating a List: To create a list, you can use square brackets [] and separate the elements with commas.pythonCopy codemy_list = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "cherry"] mixed_list = [1, "hello", 3.14, True] empty_list = []
  2. Accessing Elements: You can access elements in a list by using their index, starting from 0 for the first element.pythonCopy codefirst_element = my_list[0] second_element = fruits[1]
  3. Slicing: You can extract a subset of elements from a list using slicing.pythonCopy codesome_elements = my_list[1:4] # Gets elements at index 1, 2, and 3
  4. Modifying Lists: Lists are mutable, so you can change their contents.
    • Adding elements:
      • append(): Add an element to the end of the list.
      • insert(): Insert an element at a specific index.
    pythonCopy codefruits.append("orange") fruits.insert(1, "grape")
    • Removing elements:
      • remove(): Remove the first occurrence of a specific value.
      • pop(): Remove an element by index and return it.
    pythonCopy codefruits.remove("banana") popped_element = fruits.pop(2)
  5. List Length: You can find the number of elements in a list using the len() function.pythonCopy codenum_elements = len(fruits)
  6. List Concatenation: You can concatenate two or more lists using the + operator.pythonCopy codecombined_list = fruits + ["kiwi", "melon"]
  7. Sorting: You can sort a list using the sort() method (in-place) or the sorted() function (creates a new sorted list).pythonCopy codefruits.sort() # Sorts the list in-place sorted_fruits = sorted(fruits) # Creates a new sorted list
  8. List Comprehensions: List comprehensions are a concise way to create lists based on existing lists.pythonCopy codesquares = [x ** 2 for x in range(1, 6)] # Creates a list of squares from 1 to 5

These are some of the basic operations you can perform with Python lists. Lists are a fundamental data structure and are widely used in Python programming for various tasks.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)