Site icon 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

Modifying Lists

Other List Operations

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..

Exit mobile version