List Operation

List Operation

List Operation

List Operation

Here are some basic list operations in Python:

  • Creating a list:
				
					my_list = [1, 2, 3, "hello", True] 
				
			

This creates a list with 5 items, including an integer, two more integers, a string, and a boolean value.

  • Accessing an item in a list:
				
					print(my_list[3]) # prints "hello" 
				
			

This accesses the 4th item in the list, which is the string “hello”. Note that list indexes start at 0, so the 4th item has index 3.

  • Slicing a list:
				
					print(my_list[1:4])                  # prints [2, 3, "hello"] 
				
			

This creates a new list with items from index 1 (inclusive) to index 4 (exclusive), which are the integers 2 and 3 and the string “hello”.

  • Modifying a list:
				
					my_list[0] = 4 print(my_list) # prints [4, 2, 3, "hello", True] 
				
			

This changes the first item in the list from 1 to 4.

  • Adding an item to the end of a list:
				
					my_list.append("world") print(my_list)
 # prints [4, 2, 3, "hello", True, "world"] 

				
			

This adds a new item, the string “world”, to the end of the list.

  • Removing an item from a list:
				
					my_list.remove(2) print(my_list) 
# prints [4, 3, "hello", True, "world"] 

				
			

This removes the first occurrence of the integer 2 from the list.

These are just a few basic list operations in Python, but there are many more methods and functions that can be used with lists.

Join To Get Our Newsletter
Spread the love