List, tuple and dict
List
A list is a collection of items that are ordered and changeable. Lists are defined by enclosing the elements in square brackets []
.
Accessing elements
The elements of a list can be accessed using the index of the element. The index starts from 0.
Slicing
Slice of a list is a part of the list. Slicing is done using the colon :
operator.
Modifying elements
Elements of a list can be modified by assigning new values to the index.
List methods
Python provides several methods to work with lists. Some of the commonly used methods are:
append()
: Adds an element at the end of the list.insert()
: Adds an element at the specified position.remove()
: Removes the first occurrence of the element with the specified value.pop()
: Removes the element at the specified position.sort()
: Sorts the list.reverse()
: Reverses the order of the list.
Multi-dimensional lists
A list can contain other lists.
Tuple
A tuple is a collection of items that are ordered and unchangeable. Tuples are defined by enclosing the elements in parentheses ()
.
The difference between a list and a tuple is that a tuple is immutable, i.e., the elements of a tuple cannot be changed.
Dictionary
A dictionary is a collection of items that are unordered, changeable, and indexed. Dictionaries are defined by enclosing the elements in curly braces {}
. Each element in a dictionary is a key-value pair.
In this example, name
, age
, and city
are the keys, and Alice
, 25
, and New York
are the values.
Last updated