Data Structures allow us to store and organize data efficiently.
This will allow us to easily access and perform operations on the data.
In Python, there are four built-in data structures
- List
- Tuple
- Set
- Dictionary
List
List is the most versatile python data structure. Holds an ordered sequence of items.
Creating a List
Created by enclosing elements within [square] brackets. Each item is separated by a comma.
Code
PYTHON
Output
Creating a List of Lists
Code
PYTHON
Output
Length of a List
Code
PYTHON
Output
Accessing List Items
To access elements of a list, we use Indexing.
Code
PYTHON
Output
Iterating Over a List
Code
PYTHON
Output
List Concatenation
Similar to strings,
+
operator concatenates lists.Code
PYTHON
Output
Adding Items to List
Code
PYTHON
Output
Repetition
*
Operator repeats lists.Code
PYTHON
Output
List Slicing
Obtaining a part of a list is called List Slicing.
Code
PYTHON
Output
Extended Slicing
Similar to string extended slicing, we can extract alternate items using step.
Code
PYTHON
Output
Converting to List
list(sequence)
takes a sequence and converts it into list.Code
PYTHON
Output
Code
PYTHON
Output
Lists are Mutable
- Lists can be modified.
- Items at any position can be updated.
Code
PYTHON
Output
Strings are Immutable
Strings are Immutable (Can’t be modified).
Code
PYTHON