0% found this document useful (0 votes)
6 views22 pages

Programming I

This document covers basic data structures in Python, including lists, tuples, dictionaries, and sets. It explains how to manipulate these structures, highlighting their characteristics, methods, and operations. Understanding these data structures is essential for effective programming in Python.

Uploaded by

mamydialloawa07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views22 pages

Programming I

This document covers basic data structures in Python, including lists, tuples, dictionaries, and sets. It explains how to manipulate these structures, highlighting their characteristics, methods, and operations. Understanding these data structures is essential for effective programming in Python.

Uploaded by

mamydialloawa07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Programming I

Lecture 6: Basic data structure: lists, tuples, dictionaries


and Sets

Ms Samb
Engineer ML
Manipulating list, tuples and dictionaries

A data structure is not only used for organizing the data. It is also used for
processing, retrieving, and storing data. There are different basic and advanced
types of data structures that are used in almost every program or software system
that has been developed. So we must have good knowledge about data structures.

Manipulating lists, tuples, and dictionaries in Python is a fundamental part of


programming in the language. These data structures serve different purposes and
have specific methods and operations associated with them.

2
Manipulating List, Tuples and Dictionaries

List
A list is an ordered collection of arbitrary objects between the square brackets
i.e [ ]. We can define a list of strings, a list of numbers, a list having both names
and numbers or containing other lists in it.
>>>list_of_numbers = [2,5,7,11,13,17,19,23]
>>>list_of_strings = [“Python”,”Jawa”,”C”]
>>>list_of_mixture = [2,5,7,11, “python”, “jawa”]
>>>list_of_containing_list = [1,4,6,[“name”, “country”]]

Important thing about a list is that items in a list need not be of the same type. 3
List indexing or List indexing or access

You can get an item by referring to its position in the list, a number called the
index. The first index is zero, the second index is one, and so forth.

>>>print(list_of_strings[0],"\n")

>>>print(list_of_numbers[0],"\n")
4

>>>print(list_of_mixture[0],"\n")
Manipulating Lists, Tuples and dictionaries
Slicing
As we show, indexing allows you to access only a single cell of a list. What if we want
to get a sublist of the list. Or we want to update a bunch of cells at once? Or we want
to go on a frenzy and extend a list with an arbitrary number of new cells in any
position?

>>>print(list_of_numbers[2:5]) 5
Modifying a list
A list can be modified i.e adding items, removing items, inserting items etc. We use concepts like append,
remove, insert etc to modify the list.
Appending items
You can add an item to the end of the list with append()
>>>list_of_names.append(10)

Inserting an item in a list


insert() is an inbuilt function in Python that inserts a given element at a given index in a list.
6
>>>list_of_strings.insert(1,"DAUST")
Modifying a list

Replacing item in list


>>>list_of_numbers=[2,5,7,11,13,17,19,23]
>>>list_of_numbers[0]=4

7
Manipulating list, tuples and dictionaries
tuples
Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are list, set, and dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples in Python are similar to lists in many ways, but they have a few key differences:

Immutable: The most significant difference between tuples and lists is that tuples are immutable, while
lists are mutable. Once you create a tuple, you cannot change its elements or size. This immutability
makes tuples useful in situations where you want to ensure that the data cannot be modified
accidentally.
Syntax: Tuples are defined using parentheses () rather than square brackets [] used for lists.
Elements: Tuples can contain elements of different data types, just like lists. 8

Here's how you create and work with tuples in Python:


Tuples
Creating Tuples:
>>>my_tuple = (1, 2, 3)

Accessing Elements:
You can access tuple elements using indexing, just like lists:

print(my_tuple[0]) # Access the first element (index 0)


Tuple Packing and Unpacking:
You can create a tuple by "packing" values together:

name = "John"

age = 30
9

person_tuple = name, age # Packing values into a tuple


Tuple Methods
Tuples have some methods for basic operations:
● count(value): Returns the number of times a value appears in the tuple.
● index(value): Returns the index of the first occurrence of a value in the
tuple.
my_tuple = (1, 2, 2, 3, 4, 2)
count_two = my_tuple.count(2) # Returns 3
index_three = my_tuple.index(3) # Returns 3
Tuples can be used when you want to preserve the order of elements but
prevent them from being modified.

10
Dictionaries

Dictionaries in Python are a versatile and widely used data structure that
allows you to store and retrieve data in a key-value pair format. Each value in a
dictionary is associated with a unique key, making it easy to look up and
manipulate data. Here's how dictionaries work in Python:

11
Creating a Dictionary

You can create a dictionary using curly braces {} or the dict() constructor:

my_dict = {"name": "John", "age": 30, "city": "New York"}


my_dict = dict(name="John", age=30, city="New York")

12
Accessing Values

You can access values in a dictionary by specifying the key inside square
brackets:

print(my_dict["name"]) # Access the value associated with the "name" key

13
Modifying Values

You can change the value associated with a key:

my_dict["age"] = 31 # Update the value associated with the "age" key

To add a new key-value pair:

my_dict["job"] = "Engineer" # Add a new key-value pair

To remove a key-value pair, you can use the del statement:

del my_dict["city"] # Remove the key-value pair with the key "city" 14
Dictionary Methods

Dictionaries have several methods for performing operations like getting keys,
values, or items, checking for key existence, and more. Some commonly used
methods include:

● keys(): Returns a list of all keys in the dictionary.


● values(): Returns a list of all values in the dictionary.
● items(): Returns a list of tuples (key-value pairs).
● get(key, default): Returns the value associated with the key if it exists,
or a default value if the key is not found.
● pop(key, default): Removes the key-value pair with the specified key and
returns the value. If the key is not found, it returns the default value. 15
Dictionary Methods

keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
job = my_dict.get("job", "Unknown")
removed_value = my_dict.pop("age", None)

16
Sets in python
In Python, a set is an unordered collection of unique elements. Sets are
commonly used when you need to store a collection of items where each item
must be unique, and the order of items does not matter. Sets are defined using
curly braces {} or the set() constructor.

Here's how you can create and work with sets in Python:

Creating Sets: You can create a set by enclosing a comma-separated list of


elements within curly braces {} or by using the set() constructor.

17
Sets in python

# Creating a set using curly braces


my_set = {1, 2, 3}

# Creating a set using the set() constructor


another_set = set([4, 5, 6])

18
Sets in python

Adding and Removing Elements


You can add elements to a set using the add() method and remove elements
using the remove() method. If you attempt to remove an element that doesn't
exist, it will raise a KeyError.
>>> my_set.add(4) # Adds the element 4 to the set
>>> my_set.remove(2) # Removes the element 2 from the set

19
Sets in python
Set Operations
Sets support various set operations such as union, intersection, difference, and
symmetric difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1.union(set2) # Union of two sets


intersection_set = set1.intersection(set2) # Intersection of two sets
difference_set = set1.difference(set2) # Set difference (elements in set1 but
not in set2)
symmetric_difference_set = set1.symmetric_difference(set2) # Symmetric
difference 20
Sets in Python

Set Membership
You can check if an element is in a set using the in keyword.
if 3 in my_set:
print("3 is in the set")

21
22

You might also like