Variables & Data Types in Python | Python Basics
One of the first things we learn when we get started with any programming language is the various kinds of Data Types present and the syntax of defining variables. Now what are data types and variables?
Well you can think of variables as a container which stores some value/ data. It basically refers to a location in the memory of the computer (RAM) that is used to store a value.
Now this data stored can be of various types:
int
(integer): Whole numbers, for example 1, 2, -5 etcstr
(string): A sequence of characters, for example “hello”, “how are you?”.float
: Decimal numbers like 0.4, 1.45, 2.00003 etcbool
(boolean): True or Falselist
: Used to store a sequence of data in a single variable. For example [“apple”, “ball”, “python”], [1,4,123,53,10].tuple
: Stores a sequence of data just like a list but the only difference being that once assigned the data in a tuple is immutable (cannot be changed).dict
(dictionary): Used to store data in the form of “key” and “value” pairs.set
: Stores a collection of data in a single variable like a list. The difference being the items are unordered and there can be no duplicate elements.
All these different types of data that can be stored in a variable are called as Data Types.
Now, let’s see examples of how to define and utilise each of these data types in python.
# Sample usages of various Data Types
# Integer
a = 10
# String
a = "Hello World!"
# Float
a = 1.4234
# Boolean
a = True
# List
a = ["apple", "ball", "python"]
b = [1,2,123,41,1785]
# Tuple
c = (12,24,75)
# Dictionary
a = {"winter":"cool", "summer":"hot"} # The format is {"key":"value"}
# Set
a = {"apple", "ball", "programming"}
Working With Python Data Types
String
Strings in python can be enclosed within single (' ')
, double (" ")
or triple (''' '''
or """ """
). So 'hello'
, "hello"
, '''hello'''
all are valid strings.
name = "CodeMaple"
print(name) # The output would be "CodeMaple"
Accessing Characters
You can access individual characters in a string using indexing
message = "Hello"
print(message[0]) # Output: 'H'
print(message[2]) # Output: 'l'
String Concatenation
We can concatenate strings together using the + operator
first_name = "James"
last_name = "Bond"
full_name = first_name + " " + last_name
print(full_name) # Output: 'James Bond'
String Formatting
String Formatting helps us insert variable data in between our string, it’s like fill-in-the blanks where we create blanks in a string which is filled up with the value of the variables.
There are 2 ways to achieve this let’s explore both of them.
- Using f-strings. (New way, works only with Python 3.6 and later versions)
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # My name is Alice and I am 30 years old.
2. The old way of string formatting
Note : %s
is used to refer to string variables, %d
for integer variables and %f
for floating variables
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old."%(name, age)
print(formatted_string) # My name is Alice and I am 30 years old.
Important String Methods
Python provides various in-built methods with all the data types which do certain functions for us helping write programs efficiently and reducing our effort. Some important methods that will be useful are:
len()
: Returns the length of the string.upper()
: Converts the string to uppercase.lower()
: Converts the string to lowercase.
Let’s have a look at some examples
text = "Hello, World!"
print(len(text)) # Output: 13
print(text.upper()) # Output: "HELLO, WORLD!"
print(text.lower()) # Output: 'hello, world!'
Escaping Characters
We need to use backslask \
to print some special characters.
\n
: New line\t
: Tab\”
: Double quote. Since double quote represents the start or end of a string if you actually want to use a double quote inside a string you will need to use\”
.\’
: Single quote. This is also required for a similar logic as double quote.\\
: Backslash. Since backslash is used for the escaping characters, if we want to use a backslash we need to use a double backslash in place of it.
Examples
print("This is 1st line\nThis is line 2")
"""
Output:
This is 1st line
This is line 2
"""
List
Accessing elements
Elements in a list are accessed based on their index starting from 0 referring to the first element. Python also supports reverse indexing, so the index -1 refers to the first element from the end and -2 refers to the second last element.
Note: the len()
function is used to get the length of the list. For example len(sample_list)
would give the length of sample_list
.
word_list = ["apple", "ball", "python"]
num_list = [1,2,123,41,1785]
print(word_list[0]) # The output would be "apple" since it's the first element
print(num_list[2]) # The output would be 123 since it's the second element
print(num_list[-1]) # The output would be 1785 since it's the first element from the end
print(word_list[-2]) # The output would be "ball"
print(len(word_list)) # The output would be 3 which is the number of elements in the list
Modifying the value of an element
We can directly modify elements by accessing them through their index.
word_list[0] = "watch" # Modifying the first element in the list
print(word_list) # The output would be ["watch", "ball", "python"]
Adding an element to the end of the list
The append
method is used to add an element at the end of a list.
word_list.append("lemon") # Adds an element to the end of the list
print(word_list) # The output would be ["watch", "ball", "python", "lemon"]
Inserting an element at a given Index
The insert
method is used to add an element at a given index in the list. The syntax being sample_list.insert(<index>, <element_to_be_inserted>)
word_list.insert(1, "orange") # Inserts the element to the 1st index
print(word_list) # The output would be ["watch", "orange", "ball", "python", "lemon"]
Removing element at a specified position
The pop
method is used to remove an element at a given index.
word_list.pop(2) # Removes the element at the 2nd index
print(word_list) # The output would be ["watch", "orange", "python", "lemon"]
Removing a specific value from the list
The remove
method is used to remove the first element matching the specified value.
word_list.remove("python") # Removes the first occurence of "python" in the list
print(word_list) # The output would be ["watch", "orange", "lemon"]
Sorting the elements in a list
The sort
method is used to sort the elements in a list. The list is sorted in ascending order by default. The reverse
parameter can be used to sort the list in descending order too.
Note: In a list of strings, the elements are sorted in dictionary order.
animals_list = ["tiger", "zebra", "cow", "horse"]
num_list = [34, 3, 10, 45, 100]
animals_list.sort() # Sorts the list in ascending order
print(animals_list) # The ouput would be ["cow", "horse", "tiger", "zebra"]
num_list.sort(reverse=True) # Sorts the list in descending order
print(num_list) # The output would be [100, 45, 34, 10, 3]
Reversing a list
The reverse
method is used to reverse the elements in a list.
animals_list = ["tiger", "zebra", "cow", "horse"]
animals_list.reverse() # Reverses the list
print(animals_list) # The output would be ["horse", "cow", "zebra", "tiger"]
Slicing a list
Using slicing in python we can get access to specified slices of a list.
The format for slicing the list is [start:end:step]
.
start
is the index where we begin slicing, end
is the index where slicing ends and step
sets the gap between the next chosen element within the range of start
and end
.
We can skip providing any or all among start
, end
and step
in which case Python takes default values in place of them. The default value for start
is index 0
, for end
it’s the <length_of_list>th
index and for step
it’s 1
step.
Have a look at the examples below to get an idea of how it’s used
animals_list = ["tiger", "zebra", "cow", "horse", "dog"]
print(animals_list[:]) # Its same as printing the entire list. Output is ["tiger", "zebra", "cow", "horse", "dog"]
print(animals_list[2:]) # The output would be ["cow", "horse", "dog"]
print(animals_list[:3]) # The output would be ["tiger", "zebra", "cow"]
print(animals_list[1:3]) # The output would be ["zebra", "cow"]
# Example for using step
print(animals_list[0:4:2]) # The output would be ["tiger", "cow"]
So, in the above example animals_list[:]
was equivalent to animals[0:5:1]
which is covering the entire list with step value 1 which is exactly like printing the entire list as it is.
Extending a List (Adding items of one list to another)
The extend
method can be used to add the items of one list to another.
Have a look at the example below
animals_list1 = ["tiger","cow"]
animals_list2 = ["zebra", "horse", "dog"]
animals_list1.extend(animals_list2)
print(animals_list1) # The output is ["tiger", "cow", "zebra", "horse", "dog"]
Tuple
Same as a list, elements are accessed based on their index starting from 0. But unlike in a list, we cannot change a tuple in any way once defined, so we cannot add, remove, or modify any element.
Note: We use square brackets to define a list []
. In case of a Tuple we use round brackets ()
.
c = (12,24,75)
print(c[1]) # The output would be 24 since it's the second element
Dictionary
In a dictionary, the “key” is used to access its corresponding “value”. There cannot be duplicate keys in a dictionary. Have a look at the example below.
season_dict = {"winter":"cool", "summer":"hot"}
if "winter" in season_dict.keys():
print("Hey")
print(season_dict["winter"]) # The output would be "cool" as it's the value associated to the key "winter"
Adding new key-value pairs in a dictionary
We can add new key-value pairs in a dictionary in the following way
sample_dict = {} # Defining an empty dictionary
sample_dict["city"] = "Mumbai"
sample_dict["temperature"] = 30
print(sample_dict) # The output is {"city":"Mumbai", "temperature":30}
Deleting a key-value pair from the dictionary
There are primarily two ways to delete a key-value in Python. Let’s have a look at them.
del sample_dict[“city”]
sample_dict.pop(“city”)
Both of these methods can be used to remove the key-value pair corresponding to the key “city”.
del sample_dict["city"]
print(sample_dict) # The output is {"temperature":30}
Note : Trying to delete a key that does not exist in the dictionary will throw an error. To avoid that we can add a default return value to the pop method which is returned in case the specified key is unavailable. The syntax is sample_dict.pop(<key_to_delete>, <default_return_value>)
ret_value = sample_dict.pop("apple",-1)
print(ret_value) # The output will be -1 since the key "apple" does not exist.
Adding the key-value pairs of one dictionary to another
We can use the update
method to add the key-value pairs of one dictionary to another.
country_capitals1 = {"France":"Paris", "India":"New Delhi"}
country_capitals2 = {"Japan":"Tokyo", "Italy":"Rome"}
country_capitals1.update(country_capitals2)
print(country_capitals1) # The output will be {'France': 'Paris', 'India': 'New Delhi', 'Japan': 'Tokyo', 'Italy': 'Rome'}
Set
The Set is a collection of unique elements. Some basic properties of sets are:
- Sets are unordered which means we cannot access the elements by index.
- Sets are immutable which means that there is no way to change the value of an existing element. We can only add or remove elements from a set.
Note : An empty set is defined with set()
and NOT with a {}
as this represents an empty dictionary.
We define sets in the following way
sample_set = {"apple", "banana", "mango", "cherry"}
empty_set = set() # We define an empty set with this syntax and not {} as that represents an empty dictionary
print(len(sample_set)) # The output would be 4 since there are 4 elements in the set.
Adding elements to the set
We can use the add
method to add elements to a set
sample_set.add("pear")
print(sample_set) # The output would be {"apple", "banana", "mango", "cherry", "pear"}
Removing elements from a set
We can use the remove
or discard
method to remove elements from a set
sample_set = {"apple", "banana", "mango", "cherry"}
sample_set.remove("apple") # Will give error if "apple" is not present in set
print(sample_set) # Output: {"banana", "mango", "cherry"}
sample_set.discard("banana") # Will not give error if element is not present in set
print(sample_set) # Output: {"mango", "cherry"}
Adding sets
We can add items from one set to another using the update
method
fruits = {"apple", "banana", "cherry"}
extra_fruits = {"orange", "grape", "banana"}
fruits.update(extra_fruits)
print(fruits) # Output: {"apple", "cherry", "grape", "banana", "orange"}
If you’re an enthusiastic programmer and interested in learning Python, Web Development, DSA and System Design, join my FREE coding club where we collaborate on projects, have discussions on technical topics and help each other. Link to Discord Server
If you found this article helpful, please do give claps and follow me.
Happy Learning :)