Thursday 18 January 2024

List

 my_list = [1, 2, 3, 4, 5]

length_of_list = len(my_list)

add elements to the list

my_list = [1, 2, 3, 4, 5] # Add a new item (e.g., 6) to the list my_list.append(6)

add elements from another iterable:

# Using the + operator my_list = my_list + [7] # Using the extend() method my_list.extend([8]) print(my_list)

To combine (concatenate) two lists in Python
  1. Method 1
list_combined = [list1, list2]
  1. Using the + Operator:
list1 = [1, 2, 3] list2 = [4, 5, 6] # Use the + operator to concatenate the two lists combined_list = list1 + list2 print("Combined list:", combined_list)

  1. Using the extend() Method:
list1 = [1, 2, 3] list2 = [4, 5, 6] # Use the extend() method to add elements from list2 to list1 list1.extend(list2) print("Combined list:", list1)

In this example, list1.extend(list2) adds all elements from list2 to the end of list1.

To get a position of an item in list
fruits = ['apple', 'banana', 'cherry'] 

x = fruits.index("cherry") 

print(x)


# Return 3


Minus index: The index -1 represents the last element, -2 represents the second-to-last element, and so on.

No comments:

Post a Comment

Mức thuế ở Úc từ 07/2024

Chính phủ Úc đã thay đổi các mức thuế suất cho thu nhập cá nhân và các mức thu nhập (được gọi là ‘ngưỡng’) áp dụng những thuế suất này. Việc...