Python Data Structure
Python Data Structure
• To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
• list1 = ['physics', 'chemistry', 1997, 2000];
• list2 = [1, 2, 3, 4, 5, 6, 7 ];
• print ("list1[0]: ", list1[0])
• print ("list2[1:5]: ", list2[1:5])
Python Data Structures
Accessing Python List
To access values in tuple, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
Accessing Tuple Items with Negative
Indexing
• Negative indexing in Python is used to access elements from
the end of a tuple, with -1 referring to the last element, -2 to
the second last, and so on.
• We can also access tuple items with negative indexing by using
negative integers to represent positions from the end of the
tuple.
Accessing Range of Tuple Items
with Negative Indexing
By range of tuple items, we mean accessing a subset of elements
from a tuple using slicing. Therefore, we can access a range of
tuple items with negative indexing by using the slicing operation
in Python.
Access Tuple Items with Slice
Operator
• Syntax:
• In the example below, we are defining a dictionary named
"capitals" where each key-value pair maps a state to its
capital city. Then, we use the get() method to retrieve the
capital cities of "Gujarat" and "Karnataka"
Change Dictionary Items
• We can add dictionary items in Python using various ways such as:
• Using square brackets
• Using the update() method
• Using a comprehension
• Using unpacking
• Using the Union Operator
• Using the |= Operator
• Using setdefault() method
• Using collections.defaultdict() method
Add Dictionary Item Using the
update() Method
• Example
The following example shows how to create an array in Python
using the array module:
Basic Operations on Python Arrays