Care All Solutions

Lists

Lists are versatile data structures in Python used to store collections of items. They are ordered, mutable, and can contain elements of different data types.

Creating Lists

Python

# Empty list
my_list = []

# List with elements
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [10, "hello", True, 3.14]

Accessing Elements

  • Indexing: Use square brackets with the index to access elements. Indexing starts at 0.Pythonfruits = ["apple", "banana", "cherry"] print(fruits[0]) # Output: apple
  • Slicing: Access a sublist using slicing notation.Pythonnumbers = [1, 2, 3, 4, 5] print(numbers[1:4]) # Output: [2, 3, 4]

Modifying Lists

  • Append: Add an element to the end of the list.Pythonfruits.append("orange")
  • Insert: Insert an element at a specific index.Pythonfruits.insert(1, "grape")
  • Remove: Remove an element by value or index.Pythonfruits.remove("banana") del fruits[0]
  • Change elements: Modify elements by assigning new values.Pythonfruits[0] = "kiwi"

Other List Operations

  • Length: len(list) returns the number of elements.
  • Concatenation: Combine lists using the + operator.
  • Repetition: Create a new list by repeating an existing list using the * operator.
  • Checking membership: Use in and not in operators.

Example:

Python

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

How do I create a list?

You create a list using square brackets [] and enclosing the elements.

How do I access elements in a list?

Use indexing (starting from 0) or slicing.

Can I modify elements in a list?

Yes, lists are mutable, so you can change elements by assigning new values.

What is the append() method?

It adds an element to the end of the list.

What is the remove() method?

It removes the first occurrence of a specified value from the list.

Can a list contain elements of different data types?

Yes, a list can contain elements of different data types.

What is the time complexity of appending to a list?

Appending to a list is generally an O(1) operation.

Read More..

Leave a Comment