Wednesday

Learn Python Easy Way - Part 3

We will look at the sequential data types in Python. They are Strings, Lists and Tuples. You can access a single character in a string by its index.

For Example

Saying = "A Friend in need in a Friend indeed"
print(Saying[0], Saying[3], Saying[4],Saying[7])
A r i d


Thus you can access any character from a string by mentioning it's index number. The index numbers are counted from 0 onward. This Saying[0] indicates the character in the string in the 0th position. Whereas you can also use negative numbering for indexes. Thus -1 indicated the last character in a string. And -2 will be the second character from the end and so on.


Lists


List in Python is a ordered sequence, it may contain any of the allowed elements in Python. Thus a List may include strings, numbers, special characters, mathematical statements etc.

stateCapitals = ["Mumbai", "Delhi", "Calcutta", "Hyderabad","Bengluru"]
print("Capital of Maharashtra is "+ stateCapitals[0])
Capital of Maharashtra is Mumbai

myNumbers=[15,54,87,99,67]
print("The Fourth number in the list is" , myNumbers[3])
99
       
A list can be empty, A list can consists of names, numbers, or mixed. A list can be nested. 

You can append an item to a list or insert an item at a location in a list or remove an item from a location in a list.

Let us look at examples of working with elements in a list. 

stateCapitals.append("Ahmedabad") 
print("The capital of Gujarat used to be", stateCapitals[5])
 The capital of Gujarat used to be Ahmedabad

stateCapitals.insert(5,"Gandhinagar")
print("However, the present capital of Gujarat is ", stateCapitals[5])
 However, the present capital of Gujarat is  Gandhinagar

mylist = ["Maharashtra",["Mumbai","Pune","Nagpur"]]
print("These are some of the important cities in ", mylist[0]," - ", mylist[1][0], mylist[1][1], mylist[1][2])
  These are some of the important cities in  Maharashtra  -  Mumbai Pune Nagpur


One more interesting built in method/function in lists is to count the number of occurrences of an element in the given list. Let us look at an example

mylist = ["potato", "banana", "orange", "banana", "pomegranate","banana"]
print(  "The term banana has appeared ", count.mylist("banana"), " Times in this list")
  The term banana has appeared  3  Times in this list

You can slice the elements in a list.

myList = [9, 7, 34, 67, 81, 40, 25]
print(myList[1:5])
[7, 34, 67, 81]

This will print the list starting from the number at location 1 till the 5th (excluding 5th that is). Remember that the counting of elements in a list begins from 0.

So lists are a versatile Data type in Python that can allow you to do many interesting things that we will see in further articles. 

Featured Post

Creating Games in Scratch for ICSE Class 6

An Introduction to Creating Games in Scratch  for ICSE Class 6 Hello friends, I hope you have already read the previous post on An Int...