In this tutorial, you will learn
1. How to define a Number in Python?
2. How to define a String in Python?
3. How to concatenate string?
4. How to perform slicing and indexing on strings?
5. Whats are Lists? How to define a List in Python?
6. How to perform slicing and indexing on Lists?
7. How to define a Nested List?
1. Numbers
Python supports three types of numeric data types: integer (int), float, complex.
print(type(2)) >>> <class 'int'> print(type(2.0)) >>> <class 'float'> print(type(2+2j)) >>> <class 'complex'> # Integers 2+2 >>> 4 # Float 10/2 >>> 5.0
Python also supports every mathematic operation like addition, subtraction, multiplication and, division. Python also provides various other operations such as modulus, squaring, and much more.
# Getting an integer on division 18//3 >>> 6 # Remainder of the division 18 % 5 >>> 3 # Squaring a number 2**5 >>> 32
2. Strings
This section focuses on Python string manipulation. We can define a string in single quote ‘ ‘ and double quotes ” “. Strings are immutable. A lot of manipulation can be done on strings i.e slicing, indexing, concatenating and much more.
string_example="This is an example" print(string_example) >>> This is an example
Strings can be concatenated using + operator.
print("Python " + "3.6.7") >>> Python 3.6.7
Strings are immutable. When you try to perform item assignment on a string, you will get a TypeError.
string_example="This is an example" string_example[5]="No" >>> TypeError: 'str' object does not support item assignment
Strings can be indexed. If you want to get a value at a particular index, it can be easily done in strings.
string_example="ABCDEFGHIJKLMNOPQRSTUVWXYZ" print(string_example[10]) >>> K
Strings can be sliced also. You can get a substring of a string just passing the starting and the ending positions of the value you want to fetch.
string_example="ABCDEFGHIJKLMNOPQRSTUVWXYZ" print(string_example[10:20]) >>> KLMNOPQRST
Python has a range of inbuilt methods. You can try them Here.
3. Lists
Lists are one of the most useful data types in Python. Lists can hold data types of different types. Lists are mutable i.e. we can perform an item assignment on a list.
example_list=[1,2,3,4,5,6,7,8,9] print(example_list) >>> [1, 2, 3, 4, 5, 6, 7, 8, 9] length_of_list=len(example_list) print(length_of_list) >>> 9
Lists also support both slicing and indexing.
example_list=[1,2,3,4,5,6,7,8,9] list_indexing=example_list[5] print(list_indexing) >>> 6 list_slicing=example_list[5:10] print(list_slicing) >>> [6, 7, 8, 9]
Lists can be nested.
# Python code showing nested lists. example_list=[[1,2,3],['A','B','C']] print(example_list[0]) >>> [1, 2, 3] print(example_list[1]) >>> ['A', 'B', 'C']
Summary
1. String: Everything inside quotes ” ” is a string in Python.
2. Strings support slicing and indexing. Strings are immutable.
3. List: They can contain heterogeneous data types. Lists are mutable in nature.