Câu hỏi phỏng vấn Python
Câu hỏi

Explain how to use Slicing in Python?

Câu trả lời

Slicing in Python is a powerful feature that allows you to extract a subset of elements from a sequence, such as a list, tuple, or string, by specifying a start, stop, and optional step index. This technique is not only useful for accessing elements but also for modifying parts of sequences.

Basic Syntax of Slicing

The basic syntax for slicing in Python is:

sequence[start:stop:step]
  • start (optional): The starting index of the slice. It defaults to 0, which is the beginning of the sequence.
  • stop (optional): The ending index of the slice. This index is not included in the slice. If omitted, slicing goes up to and including the end of the sequence.
  • step (optional): The step size or the increment between indices in the slice. If omitted, the step size defaults to 1, which means every element between start and stop is included.

Examples of Slicing

  1. Slicing a List:

    my_list = [0, 1, 2, 3, 4, 5]
    print(my_list[1:4])  # Output: [1, 2, 3]

    This slices my_list from index 1 to 3 (index 4 is not included).

  2. Using Negative Indices:

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

    Negative indices count from the end of the sequence.

  3. Using Steps:

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

    This slices my_list from index 1 to 4 with a step of 2, so it includes every second element in that range.

  4. Reversing a String:

    my_string = "hello"
    print(my_string[::-1])  # Output: "olleh"

    A negative step can be used to reverse a sequence.

Advanced Slicing

  • Omitting Indices:
    If `s...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What are the Dunder/Magic/Special methods in Python? Name a few.

middle

Explain the UnboundLocalError exception and how to avoid it?

senior

Why are Python's private methods not actually private?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào