Python Basics: List

A list in Python is like an array or a list in Java.
Still, it’s very simple to declare a Python list:

list = [1,2,3,4] <- an int type list
  list = ["2","Hello","World"] <- a string type list
  list = [] <- just to define an empty list


You can use loops to iterate through a list:

for i in list:
    print(i)

This will output all the elements in list.
You can get certain element by specifying the index:

x = list[index]
 //like in other languages, in a list or an array, indexes are always 
 starting from 0

In Python, you can specify a certain range within a list:

intList = [1,3,4,5]
 intList[2:] 
 //In which, 2 is an starting index (the element before last element in list)
 //The result does include the element at index 2.
 //this will output 4

 intList[:] 
 //If you give no index at any side (left or right), the default starting index will be 0
 //so the indexes of this line will be 0 to 0

 intList[1:3] <- Outputs the element from index 1 to index 2

 intList[:-1] 
 //in python list, an index with a minus sign means to countdown the 
 list; in this line, -1 is the index of the last element of intList; the result 
 does not include the last element 
 
 //A string can also be considered as a list
 str ="Java"
 print(str[1:]) <- output is "ava"
 //start from index 1
 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.