Example | Data Type |
---|---|
x = "Hello World" |
str |
x = 20 |
int |
x = 20.5 |
float |
x = True |
bool |
x = None |
NoneType |
x = ["apple", "banana", "apple"] |
list |
x = ("apple", "banana", "cherry") |
tuple |
x = {"name" : "John", "age" : 36} |
dict |
x = {"apple", "banana", "cherry"} |
set |
Common Python data types are listed in Exhibit 25.50.
Data types for storing sequences of values:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = ["abc", 34, True, 40, "male"]
list1[0] # returns "apple"
list1[1] # returns "banana"
list1[2] # returns "cherry"
list1[1] = "blackcurrant" # replaces "banana"
car1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car1
dictionary provides information about a specific car. You can access dictionary items using their keys, i.e.:
car1["model"] # returns "Mustang"
car1
can represent a row in a table listing cars. If you combine multiple dictionaries, such as car1
, car2
, car3
, etc., into a tuple (car1
, car2
, car3
), you create a table where each row (e.g., car1
, car2
) is a dictionary containing information about a specific car.
cars = (car1, car2, car3)
The len()
function returns the number of items in a sequence or a collection. You can use this function to determine the length of lists, tuples, dictionaries or sets. For instance, len(list1)
will return 3.
You can also use the len()
function to determine the length of a string, as strings in Python are stored as sequences of characters.
Note in Exhibit 25.50, the use of brackets in the syntax, for creating these data types and assigning values to them. An alternative approach to creating these data types is through functions such as list()
, tuple()
, dict()
and set()
.
You can also use these functions to manipulate data. For instance, in Exhibit 25.50, the set()
function is used to convert a list into a set, which automatically removes duplicate elements. The list()
function is then used to convert the set back into a list of unique elements from the original list.
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_numbers = list(set(numbers))
print("List with duplicates removed:", unique_numbers)
List with duplicates removed: [1, 2, 3, 4]
set()
and list()
to remove duplicates from a list of numbers.Use the Search Bar to find content on MarketingMind.
Contact | Privacy Statement | Disclaimer: Opinions and views expressed on www.ashokcharan.com are the author’s personal views, and do not represent the official views of the National University of Singapore (NUS) or the NUS Business School | © Copyright 2013-2025 www.ashokcharan.com. All Rights Reserved.