Programming Tutorials

(追記) (追記ここまで)

python list

By: Ashley J in Python Tutorials on 2017年09月27日 [フレーム]

In Python, a list is a mutable, ordered sequence of items. Here are some of the commonly used operations that can be performed on lists:

  1. Creating a list: To create a list, we can use square brackets [] or the list() constructor.

    Example:

    my_list = [1, 2, 3, 4, 5]
    my_list = list(range(1, 6))
    
  2. Accessing list elements: We can access the elements of a list using their index.

    Example:

    my_list = [1, 2, 3, 4, 5]
    print(my_list[0]) # Output: 1
    print(my_list[-1]) # Output: 5
    
  3. Modifying list elements: We can modify the elements of a list using their index.

    Example:

    my_list = [1, 2, 3, 4, 5]
    my_list[0] = 6
    print(my_list) # Output: [6, 2, 3, 4, 5]
    
  4. Adding elements to a list: We can add elements to a list using the append() method or the + operator.

    Example:

    my_list = [1, 2, 3]
    my_list.append(4)
    print(my_list) # Output: [1, 2, 3, 4]
    my_list = [1, 2, 3]
    my_list = my_list + [4]
    print(my_list) # Output: [1, 2, 3, 4]
    
  5. Removing elements from a list: We can remove elements from a list using the remove() method or the del keyword.

    Example:

    my_list = [1, 2, 3, 4, 5]
    my_list.remove(3)
    print(my_list) # Output: [1, 2, 4, 5]
    my_list = [1, 2, 3, 4, 5]
    del my_list[2]
    print(my_list) # Output: [1, 2, 4, 5]
    
  6. Slicing a list: We can extract a subset of a list using slicing.

    Example:

    my_list = [1, 2, 3, 4, 5]
    print(my_list[1:3]) # Output: [2, 3]
    
  7. Finding the length of a list: We can find the number of elements in a list using the len() function.

    Example:

    my_list = [1, 2, 3, 4, 5]
    print(len(my_list)) # Output: 5
    
  8. Sorting a list: We can sort a list using the sort() method.

    Example:

    my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    my_list.sort()
    print(my_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
    



(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /