Skip to main content

Python Hunter, Slicing, traversing, copy and pit falling of list and tuple in python. By Pran Sukh


Python Slicing GIF.
Slicing is a technique in python to pick up data from list,tuple and set from desired location. lets make python a bit more beautiful with slicing technique. 
Caution:- No animal is hurt during the development of this tutorial :) 
it can be done with three arguments. e.g dataString [begin: end: step] argument begin and end are giving lucid view, these arguments are to instruct the script that from where the slicing will begin and where it will end, but the tricky argument is the last one ("step"). it indicates that how many index or indices the code have to hops or skip to pick up the next slice. In the below example the slicing is starting form 6th index or indices and go till 21th index and after every slice it will skip the 3 index or indices between the begin and end index. 


let's take an example :-

1
25
str = "1abcdefghijklmnopqrstuvwxyz"

print(str[6:21:3])
list_1 = ["This","cat","is"]
print(list_1[0:2:1])


Output:-
>>filor

Code Explanation:- 

begin = 6
end = 21
step = 3

index to pick = 6 + 3 = 9th index


9 + 3 = 12
12 + 3 = 15
15 + 3 = 18
18 + 3 = 21
but magnify you output and run series of cases.... if any index is equals to your end value that index will not be picked up. according to the logic the character at 21th index should be picked up but it is also the end of slicing so that is why the 'u' will never be picked up, but if you change the end value from 21 to 22 then character at 21th index 'u' will be picked up. 


Concatenation of list and tuple 
Concatenation in Python is just like adding number concatenation or combining of strings, list and tuple is easy, and that is too with `+` operator.

Example 1 (Concatenating strings) 
1
2
3
4
string_1 = "Python"
string_2 = "Hunter"
print("Concatenating string_1 and string_2")
print(string_1 +" "+ string_2)#PythonHunter

Output:-
>>Concatenating string_1 and string_2
>>Python Hunter


Example 2 (Concatenating Lists)
1
2
3
4
list_1 = ["This","cat","is"]
list_2 = ["of","black","color"]
print("Concatenating list_1 and list_2")
print(list_1 + list_2)

Output:-
>>Concatenating list_1 and list_2
>>['This', 'cat', 'is', 'of', 'black', 'color']



Example 3 (Concatenating Tuples)

1
2
3
4
tuple_5 = ("This","is")
tuple_6 = ("Python","Hunter")
print("Concatenating tuple_5 and tuple_6")
print(tuple_5 + tuple_6)

Output:-
>>Concatenating tuple_5 and tuple_6
>>('This', 'is', 'Python', 'Hunter')

Note:- only similar data types can be concatenated, it is not allowed to concatenate string with list or list with tuple or tuple with string


Check If element is there or not

We all have sense of questioning thing. we might question a list,string and tuple that whether it contain
any specific element or not. For this purpose we can you 'in' and 'not in' operators.

Example(s):-

12
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
string_1 = "PythonHunter"
print( 'e' in string_1) # true
print( 'k' in string_1) # flase

print( 'e' not in string_1) # flase. 'e' is present in string
print( 'k' not in string_1) # true. cos there is no 'k' in the string

list_1 = ["This","is","PythonHunter"]

print( 'PythonHunter' in list_1) # true
print( 'PythonKiller' in list_1) # flase

print( 'PythonHunter' not in list_1) # flase. 'PythonHunter' is present in list
print( 'PythonKiller' not in list_1) # true. cos there is no 'PythonKiller' in the list

tuple_1 = ('This','is','tuple')
print( 'This' in list_1) # true
print( 'cat' in list_1) # flase

print( 'This' not in list_1) # flase. 'PythonHunter' is present in list
print( 'cat' not in list_1) # true. cos there is no 'PythonKiller' in the list

Output:- (run the code and get output, run a series of code and observe the output)

Repetition

We don't want to do the tedious jobs of writing the same code for over and over again. For that python have gave us the '*' operator, since multiplication of sequential data like string, list, tuple, dictionary or set is not possible but  '*'  operator makes copies of these sequential data.
e.g. if we want to print '#' for 10 times we no need to write
print('##########')
This code can be replaced by
print('#'*10)
with list and tuple also..
list_0 = ['Python','Hunter']
print( list_0 * 3 )
it will repeat list's elements for 3 times in single list.
Lets do this with list and tuple

1
2
3
4
5
list_0 = ['Python','Hunter']
print( list_0 * 3 )

tuple_1 = ('This','is','tuple')
print( tuple_1 * 3 )

Pit falling


The advantage of repetition can be used to create nested lists. 
x = ["a","b","c"]
y = [x] * 4
y list will create with 4 elements and each element will be a nested list of x type.
Examples:-

1
2
3
4
5
6
7
8
9
#repetition of tuple
x = ("a","b","c")
y = (x) * 4
print(y)

#repetition of list
x = ["a","b","c"]
y = [x] * 4
print(y)


Lets change the elements of nested list and see what happens.

1
2
y [0] [0]= "H"
print(y)
Output will be:-
1
[['H', 'b', 'c'], ['H', 'b', 'c'], ['H', 'b', 'c'], ['H', 'b', 'c']]

This can blow your mind. we are altering the 1st element of 1st nested list but this change will reflect in other elements too, why...?

Run the following code and observe the output, the memory location of elements with id() function.

Code:-

1
2
3
4
5
print("Memory location of element at x[0]:-", id(x[0]))
print("Memory location of element at y[0][0]:-", id(y[0][0]))
print("Memory location of element at y[1][0]:-", id(y[1][0]))
print("Memory location of element at y[2][0]:-", id(y[2][0]))
print("Memory location of element at y[3][0]:-", id(y[3][0]))

Output:-
Memory location of element at x[0]:- 30830496
Memory location of element at y[0][0]:- 30830496
Memory location of element at y[1][0]:- 30830496
Memory location of element at y[2][0]:- 30830496
Memory location of element at y[3][0]:- 30830496
As you can see the location of element x[0] in x list is 30830496.
Now each element in y list is carrying the list of x. that means x list is repeated in each element of y list, now change in one list will reflect the change on each sub list.

(Note:- memory location may vary in your machine as it is randomly accessed by python interpreter).

Read the explanation and refer to the attached below diagram to depict the internal operation.
That is a concept of Shallow Copy and Deep Copy. The reason is, the repetition code  ' y = [x] * 4 ' has created 4 references of 'x' list, each sub list or nested list is pointing to the same original 'x' list, so any change is one reference will affect the other nested lists to because of same memory location reference.

That's it in this post, further we will discuss about dictionaries and sets in python under this link.




Thanks.....

Comments

Popular posts from this blog

XML, XSLT info by pran sukh on Python Hunter blog.

What is XML? Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost. XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data. XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data. With XML, data can be available to all kinds of "reading machines" like people, computers, voice machines, news feeds, etc. XML:- 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 31 32 33 34 35 36 37 38 39 40 41 42 <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category= "cooking" > <title lang= "en" > Every

Understanding the usage of underscore( _ ) of Python for beginner. On Python Hunter

Introduction: Just like you, a newbie in python scripting language, me too was confused about lot of new things in python that are not valid or available in other languages like Java, .Net etc. Just like other things i had seen the use of '_' underscore in python, at beginning level that flabbergasted me for a while.      With some research and practice i have summarised the following usage of '_' underscore in python. Hope you will find it helpful at beginning level. First Usage : Hold the previous output value. When used in interpreter. 1 2 3 4 5 6 7 _ = input () # For example you typed '5' print (_) # This will print '5' print ( int ( _ ) * int ( _ ) ) # This will print '25' print ( int ( _ ) + 10 ) The above will print '15', because last input was "5" and in above   line of code is producing '25' as output but not being handl

XSLT apply import tag by pran sukh on python hunter blog

Modular Programming is good attitude of best programmer. We often need to keep our code in modular approach so that is would be easy to maintain  and update or remove dead code and also it ease the process of bug tracking. XML and XSL  processors provide freedom to import multiple imports to process the same  XML  document. In the following  XML  data we have data from collage where student's and teacher's data is given. But we want to process the same  XML  data with different XSL files. Here in this example we want to show the teacher data in red background color and student data in green background color. Data.xml 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 31 32 33 34 35 36 <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "RootXSLT.xsl"?> <data> <DataFor name = "Student" id = "001" > <firstname>