Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size. They are also mutable—unlike strings and tuples, lists can be modified in place by assignment to offsets as well as a variety of list method calls.
Create lists
Storing different type of variable in a list is totally possible.
1 2 3 4 |
List_1=["apple",123,"3.14"] List_1 ['apple', 123, '3.14'] >>> |
As you see, we have three types of data ; apple is a string, 123 is an integer, 3.14 is a float number.
For some reasons, you may create an empty list. In order to populate later in your code.
1 2 3 4 |
empty_list=[] empty_list [] >>> |
Alternatively you can create an empty list by list() function.
1 2 3 4 |
empty_list2=list() empty_list2 [] >>> |
To see how many elements you have in the list use len() function.
1 2 3 4 |
List_1=["apple",123,"3.14"] len(List_1) 3 >>> |
A string can be transformed into a list by list() function.
1 2 3 4 |
s="Hello" list(s) ['H', 'e', 'l', 'l', 'o'] >>> |
Indexing
Indexing is same as strings. You can reach each element in a list by its position, index number.
1 2 3 4 5 6 7 8 |
list_1 = [3,4,5,6,7,8,9,10] list_1[0] # first element 3 list_1[5] # fifth element 8 list_1[-1] # last element 10 >>> |
Construction that we use for indexing or slicing is [start point:end point:stride]
Check following examples:
1 2 3 4 5 6 7 8 9 10 11 12 |
list_1 [3, 4, 5, 6, 7, 8, 9, 10] list_1[2:8] # takes from 2nd position (strating from 0) to 8th position (8 is not included.) [5, 6, 7, 8, 9, 10] list_1[2:8:2] # same as above but stride by 2. [5, 7, 9] list_1[:5] # starting from the beginning (0) to 5th position 5 is not included. That’s why you have 4 elements in the output [1, 4, 5, 6, 7] list_1[5:] # starting from 5th position (5th element is included) to the end of the list. [8, 9, 10] |
Nesting
We use nested lists to build a matrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Here we have a 3 * 3 matrix. 3 columns and 3 rows. x = [[1,2,3],[4,5,6],[7,8,9]] x [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # If we put them in an excel sheet: [1,2,3] [4,5,6] [7,8,9] # I want to take first rows with all columns. x[0] [1, 2, 3] # I want to take first row with 2nd and 3rd columns. x[0][1:] [2, 3] # I want to reach number “9”. So, 3rd row 3rd column. x[2][2] 9 |
Mutable lists
You can replace a value inside a list by another data type; integer, float or string by its index number.
1 2 3 4 |
list_1 = [3,4,5,6,7,8,9,10] list_1[3]="A" list_1 [3, 4, 5, 'A', 7, 8, 9, 10] |
Here we changed the 3rd position which was equal to number 6 with letter A.
Actions to perform while working with lists
You can use Python methods to perform some actions in list objects. Some of them are:
- append adds the object to the end of list
- clear Clear the list object.
- copy Copy the list object.
- count returns the number of a given element occurs in a list.
- extend add a given item in a list.
- index returns the index number of the first occurrence of an element. Gives an an exception if the element is not in the list.
- insert insert a given item in the list on a given position.
- pop remove a return the item in a given index number.
- remove delete the first occurrence of a given item from a list.
- reverse reverse the order of a list.
- sort sort elements by ascending order.
I will give exmaples for each methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
list_1 [3, 4, 5, 'A', 7, 8, 9, 10] # we have a list with these items. list_1.count(3) # element 3 is present one time. 1 list_1 [3, 4, 5, 'A', 7, 8, 9, 10] list_1.append("One") # Appending ‘one’ item at the end of list. list_1 [3, 4, 5, 'A', 7, 8, 9, 10, 'One'] list_1.pop() # returns last populated item. 'One' list_1.pop(3) # returns 3rd element (starting from position 0) 'A' list_1.pop(45) Traceback (most recent call last): # here we have index error because list is limited to index 8. File "<input>", line 1, in <module> IndexError: pop index out of range list_1.sort() # As you see here sort() method get ride of strings and preserve only integers. That’s normal because we had strings and integers in our list. If we had same data type all string or all integer in the list it could work. (in case of letters it will sort by alphabetical order). list_1 [3, 4, 5, 7, 8, 9, 10] list_1.sort(reverse=True) # reverting the sorted output. list_1 [10, 9, 8, 7, 5, 4, 3] list_1.copy() # just copies the list as it was before. (Last state is preserved). [10, 9, 8, 7, 5, 4, 3] list_1.extend("0") # adds “0” in the list but here we gave something different. list_1 [10, 9, 8, 7, 5, 4, 3, '0'] |
Let’s check the type of “0”. Its position is 7th.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
print(type(list_1[7])) # So, as you see, with extend method we added a string not integer. <class 'str'> list_1 [10, 9, 8, 7, 5, 4, 3, '0'] list_1.index(4) # index() gives the position number of number 4. 5 list_1.index(10) # 10 is located in the index 0. 0 list_1.index('0') # string 0 is located in index 7. 7 list_1 [10, 9, 8, 7, 5, 4, 3, '0'] list_1.insert(1,'a') # on first index, after 10 which is in index 0, we add ‘a’ string. list_1 [10, 'a', 9, 8, 7, 5, 4, 3, '0'] list_1.insert(0,'b') # on index 0, right before 10, we add string ‘b’ list_1 ['b', 10, 'a', 9, 8, 7, 5, 4, 3, '0'] |
Now I’ll add the string ‘ 0’ in index 0, to show you remove method.
1 2 3 4 5 6 7 8 9 10 |
list_1.insert(0,'0') list_1 ['0', 'b', 10, 'a', 9, 8, 7, 5, 4, 3, '0'] list_1.remove('0') # first occurrence of string ‘0’ is deleted. Last one remains. list_1 ['b', 10, 'a', 9, 8, 7, 5, 4, 3, '0'] list_1.clear() # Remove all elements in the list and return an empty list. list_1 [] |
Special characters in Print()
n Char
Is used to skip a new line.
1 2 3 4 |
print("PythonnJavanC++") Python Java C++ |
t Char
This character puts between words “tab” space.
Escape Sequence | Meaning |
newline | Ignored |
\ | Backslash () |
‘ | Single quote (‘) |
“ | Double quote (“) |
a | ASCII Bell (BEL) |
b | ASCII Backspace (BS) |
f | ASCII Formfeed (FF) |
n | ASCII Linefeed (LF) |
r | ASCII Carriage Return (CR) |
t | ASCII Horizontal Tab (TAB) |
v | ASCII Vertical Tab (VT) |
ooo | ASCII character with octal value ooo |
xhh… | ASCII character with hex value hh… |
Type() function
We use type() function to print data type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
a = 65 print(type(a)) <class 'int'> a = 5.87 print(type(a)) <class 'float'> a = "Hello" print(type(a)) <class 'str'> |
Print function has special parameters
Check this example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
print(3,4,5,6,7,8,9) 3 4 5 6 7 8 9 print(3,4,5,6,7,8,9,sep = ".") 3.4.5.6.7.8.9 print("06","04","2015",sep = "/") 06/04/2015 print("This","is","Python",sep = "n") This is Python |
“*” parameter
1 2 3 4 5 6 7 8 9 10 11 12 13 |
print(*"Python") P y t h o n print(*"Python",sep = "n") P y t h o n |
Formatting
Some times you want to introduce in your print function some variables as string,integer or float. This can be done easily with format() function.
Look at this example:
1 2 3 4 |
a = 3 b = 4 print("{} + {} is equal to {} ".format(a,b,a+b)) 3 + 4 is equal to 7 |
Numbers in {} tell python the order of printing variables.
1 2 |
"{1} {0} {2}".format(“!”,"Hello",”world”) Hello ! world |
Try your code here. Just delete the embed code and write your own!
Leave A Comment