Introduction

Hey guys today I am writing a tutorial on Lists and tuples in Python....

So lets get started...

Layout:-

1.What are data sturctures?
2.What are tuples?
3.What are lists?
4.inbuilt functions on lists and tupples

What are Data structure?

Anybody familiar with programming or Actually Computers. Should be knowing what are data structures. Data structures are simply a collection of data (eg:- numbers , characters etc etc.) Each element in a data structure is assigned to a unique index …In python the first element of a sequence in assigned to 0 then 1,2,3,4,5,and so on.. I'll make that easy in the next topic.

NOTE: A data structure can also contain a collection of other data structures

eg:-

Aneesh = ("Aneesh Dogra" , 15) 
Sachin = ("Sachin Sharma", 36) 
data = (Sachin , Aneesh) 

print data

output:-

(('Sachin Sharma', 36), ('Aneesh Dogra', 15))

You'll have a better understanding of the above program when I'll clear lists and tuples


Python has 6 built-in types of sequences... But in this tutorial we'll be only dealing with Two of them that is LISTS AND TUPPLES.

What are tuples?What are lists?

In Python they both are just types of sequences...
The main difference in between tuples and lists are that you can change a list or add some elements to a list but you cannot change Tuples.


Tupples:-

To declare a tuple in python we simply put no brackets or we can put '(' Tuple ')' Both works and we seperate elements in a tuple by a comma..

Eg:-

Aneesh = ('H','e','y',' ','t','h','i','s',' ','i','s',' ','A','n','e','e','s','h') 

print Aneesh

output:-
('H', 'e', 'y', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'A', 'n', 'e', 'e', 's', 'h')

Indexing:-

In the beginning of chapter I told you that Each element in a data structure is assigned to a unique index …In python the first element of a sequence in assigned to 0 then 1,2,3,4,5,and so on..

lets try that:-

Aneesh = "Hey this is Aneesh" 

print Aneesh[0] 
print Aneesh[1] 
print Aneesh[2] 
print Aneesh[3] 
print Aneesh[4] 
print Aneesh[5] 
print Aneesh[6] 
print Aneesh[7] 
print Aneesh[8] 
print Aneesh[9] 
print Aneesh[10] 
print Aneesh[11]

output:-
H
e
y

t
h
i
s

i
s

Note to Experienced Programmers: I know by writing these large pieces of code I made my program so unreadable . I could have used some loops . But as this is a tutorial for absolute beginners so I avoided to use them ..


Python also supports indexing from the last element … I'll show you how...

Aneesh = "Hey this is Aneesh" 

print Aneesh[-1] 
print Aneesh[-2] 
print Aneesh[-3] 
print Aneesh[-4] 
print Aneesh[-5] 
print Aneesh[-6] 
print Aneesh[-7] 
print Aneesh[-8] 
print Aneesh[-9] 
print Aneesh[-10] 
print Aneesh[-11]

output:-

h
s
e
e
n
A

s
i

s

When you use a negative index python starts counting from the right side..so..
The last element in a sequence is referred by a [-1] not a [-0] as that would be same as the first element . The second last element is referred by a -2 and so on...

The method of referring to elements in a sequence by this method is called Indexing..

Sequences like strings can be indexed directly... eg:-

print 'hey'[0]

output = h

I think that all about indexing now lets get to:-

Slicing

Have a slice of bread and learn about slicing... “LOL”

Slicing is somewhat related to indexing …
As you used indexes to access different individual elements in a sequence .. you can use slicing to access ranges of elements. “looks interesting” let's get to it..

Aneesh = "Hey this is Aneesh" 

print Aneesh[0:10]

output:-

Hey this i

Pretty Simple...

lets try it with some other code:-

Aneesh = "1234567" 

print Aneesh[3:6]

output : 4,5,6

Remember:- The index of 1st element in the sequence is 0.

lets try something else:-

Shortcuts:-

Aneesh = "1234567" 

print Aneesh[0:6:2]

Output:-
135

This type of slicing means … Print 0-6th elements but not everyone..
Only every second element including the first...
I'll make that easy

try with this:-

Aneesh = "1234567" 

print Aneesh[0:6:1]

Now the program says to python that print every 1st element... that actually means each one of them …
Now does that make sense?

All other shortcuts in one ..:-

no = "1234567" 

print no[:3]	# it actually means [0:3]  yes you guessed it right the 			zeroes can be omitted 
print no[:]	# if you want to print the entire sequence then you could 				use a single colon 

print no[-1:1]	#      Not exactly the desired result. In fact, any time 				the leftmost index in a slice comes later in the 				sequence than the second one the 				result is always an empty sequence. 
print no[-1:4] # empty 
print no[-5:4] # it will print  3,4 as the left element comes before the 			right one... so no empty case 

# Actually guyz thers tons of other things you can do with slicing and I think you all should mess around with them research about it on google etc etc...

I commented the source above … to make it easy to understand....

Lists:-


To declare a list in python we simple put '' at the start and end of the list respectively.
And we separate different elements in a list by a comma ','..

Eg:-

no = ['1','2','3','4','5','6','7'] 

print no[0]

output:-
1

words = ['Aneesh','You','tutorial'] 

print words[0]

output:-
Aneesh

Same slicing and indexing can go in lists also....



List Methods:-

There are some functions made for lists... like append ete etc....

The basic format of these methods are :-

object.method(arguments)

pretty simple...

Append:-

The append method is used to add an element/object at the end of the list:-

eg:-

Aneesh = ['Hello' , 'World' ] 
Aneesh.append('Welcome') 

print Aneesh

output:-

As expected....

Note : The method append only takes one argument...for appending more than 1 value we use method extend()....explained below...

Extend:-

We use this Method when we want to add more than one values/elements at the end of a list...

eg:-

Aneesh = ['Hello' , 'World' ] 
you = ['This','is','a','simple','tutorial'] 
Aneesh.extend(you) 

print Aneesh

This can seem ...Same as adding sequences [explained in the next topic] but it is not.. here the “Aneesh” list is updated....


Count:-

list1 = [1,3,4,9,0,0,8,8,7,7,7,7] 
print list1.count(7)

output:-

4

no need to explain that...

Insert :-

Insert method is used to insert an element in a list at a certain index...

eg:-

list1 = [1,3,4,9,0,0,8,8,7,7,7,7] 
list1.insert(5,"Hey hooooooooo!!!!!!") 
print list1

output:-

[1, 3, 4, 9, 0, 'Hey hooooooooo!!!!!!', 0, 8, 8, 7, 7, 7, 7]

POP :-

If you are familiar with low level programming then you'll be familiar with pop and push with stack...

The pop method removes an element from a list … By deafault the last one..
The pop also return the element it removed...

list1 = [1,3,4,9,0,0,8,8,'last'] 
print list1.pop() 
print list1

output:-
last
[1, 3, 4, 9, 0, 0, 8, 8]

In the above code The pop removed the last element....As explained above...and returned the value of the element it removed...In this case last

And if you'll give it a index it will remove that element eg:-

list1 = [1,3,4,9,0,0,8,8,'last'] 
print list1.pop(2) 
print list1

Output:-
4
[1, 3, 9, 0, 0, 8, 8, 'last']

Remove:-

Remove is somewhat similar to pop.. it takes the value of any element in the list and removes that from the list....

list1 = [1,3,4,9,0,'middle',8,8,'last'] 
list1.remove('middle')
print list1

Output:-

[1, 3, 4, 9, 0, 8, 8, 'last']

This method doesn't remove anything...

Reverse:-


It simply reverses the list....

list1 = [1,3,4,9,0,'middle',8,8,'last'] 
list1.reverse()
print list1

Output:-


Sort:-

This method simply sorts the list....

list1 = [1,3,4,9,0,8,8] 
list1.sort() 
print list1

Output:-

[0, 1, 3, 4, 8, 8, 9]

NOTE: Guys There's still some more functions...Dealing with lists but these are basic and the most used ones...

Some more stuff you can do with sequences:-

Adding sequences:-

string = "Hello" + "Aneesh" 
print string

output:-

HelloAneesh

Note : Adding strings do not automatically add a space between them you have to add it manually.

This method is also called concanteration

Multiplying:-

string = "Hello"  * 5 
print string

output:-

HelloHelloHelloHelloHello

The 'in' operator:-


In python you can check if a word , string , digit is in a sequence or not... by using the 'in' operator

It returns True if he found it , or else False if he dint found it...

Eg:-

print 'l' in "Hello"

output :-

True

as expected


Some more examples:-

nos = [10,9,8,7,6,5,4,3,2,1] 

print 1 in nos

Output:-

True

As expected...

Length , Minimum , Maximimum:-

There are 3 very useful functions in python:-

1.len
2.min
3.max

I think no need to explain them you'll be able to pick them .. only by seeing the source and the output:-

list1 = '1','3','4' 

print list1 
print "length = ",len(list1) 
print "Minimum value = ",min(list1) 
print "Maximum Value = ",max(list1)

Output:-

('1', '3', '4')
length = 3
Minimum value = 1
Maximum Value = 4


cmp [compare] :-

This method simply compare 2 values,lists,tuples and returns a 0 if the two inputs are equal, -1 if leftmost input is smaller or 1 if rightmost input is smaller...

cmp(x,y)

1 if x>y
0 if x==y
-1 if x<y

x=1 
y=2 
print cmp(x,y)

output:-

-1


At last I'd like you all to know about what is “None” and how do we initialize an empty list in python ..

As we know an empty list is initialized by “a = []” simply putting two brackets with nothing on it... But what if you want to make a list with room for 10 elements with nothing useful in it..
We use None...

a = [None] * 10 
print a

Output:-

[None, None, None, None, None, None, None, None, None, None]


Its not so useful …. You could've used zeros instead of “None” ...But you may find it in some other source codes..So... That's why I explained it...

Thanks guyz for reading this....
Feel free to add comments...

Beat_Slayer commented: Pretty nice for beginners +1

Recommended Answers

All 6 Replies

If you explain tuples, it is good to explain how to write one element tuple:

One element tuple: singleton

If you write expression or value in parenthesis, that will not make tuple. So to make tuple you need comma, so we put one:

>>> single=('single')
>>> print single
single
>>> # no success, must put comma
>>> single=('single',)
>>> print single, type(single)
('single',) <type 'tuple'>
>>>

By the way your print statements are Python 2.6, I also use that because of some module support.

You should write that in beginning of your tutorial.

Maybe this tutorial is little longish for a newbie, but good stuff!

If you explain tuples, it is good to explain how to write one element tuple:

One element tuple: singleton

If you write expression or value in parenthesis, that will not make tuple. So to make tuple you need comma, so we put one:

>>> single=('single')
>>> print single
single
>>> # no success, must put comma
>>> single=('single',)
>>> print single, type(single)
('single',) <type 'tuple'>
>>>

By the way your print statements are Python 2.6, I also use that because of some module support.

You should write that in beginning of your tutorial.

Maybe this tutorial is little longish for a newbie, but good stuff!

Sorry about those flaws ....

And thanks for reading...

One thing you have to be careful of is this tricky stumbling point (which arises because Python's lists are mutable):

>>> a = [[None]*3]*3
>>> a
 [[None, None, None], [None, None, None], [None, None, None]]
>>> a[0].append("Hello")
>>> a
 [[None, None, None, 'Hello'],
 [None, None, None, 'Hello'],
 [None, None, None, 'Hello']]
>>>

Hey guyz long time no comments...

I have a list like ['1.1881', '1.1881', '1.1881', '1.1881', '1.1881', \
'1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.7689', \
'1.7689', '3.4225', '7.7284', '10.24', '9.0601', '9.0601', '9.0601', '9.0601', '9.0601']. I want to find maximum and minimum of this list. Because of elements of list are decimals, max function of python gives the wrong maximum 9.0601 instead of 10.24.How can I find correct minimum and maximum of this list using python functions?

That is because you are comparing strings. If If all the numbers were integers or floats, 10.24 would be the max.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.