Você está na página 1de 12

 import module: nice when you are using many bits from the module.

drawback is that you'll


need to qualify each reference with the module name.
 from module import ...: nice that imported items are usable directly without module name
prefix. The drawback is that you must list each thing you use, and that it's not clear in code
where something came from.

Python Lists

 Python has a great built-in list type named "list". List literals are written within
square brackets [ ]. Lists work similarly to strings -- use the len() function and
square brackets [ ] to access data, with the first element at index 0.

colors = ['red', 'blue', 'green']
print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3

List Comprehension: Elegant way to
create new List
List comprehension is an elegant and concise way to create new list from an existing list
in Python.

List comprehension consists of an expression followed by for statement inside square


brackets.

Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]

# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

print(pow2)

new_range = [i * i for i in range(5) if i % 2 == 0]


listOfWords = ["this","is","a","list","of","words"]

items = [ word[0] for word in listOfWords ]

print items
The output should be: ['t', 'i', 'a', 'l', 'o', 'w']

QP: Read a text from the user and print out the first letter of each word in the text using list
comprehension
a="hello how r u"

#b=[]

b=a.split(' ')

print b

w=[x[0] for x in b]

print w

list comprehension in functions.


# Create a function and name it double:
def double(x):
return x*2

# If you now just print that function with a value in it, it should look like this:
>>> print double(10)
20
We can easily use list comprehension on that function.

>>> [double(x) for x in range(10)]

print double
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# You can put in conditions:

>>> [double(x) for x in range(10) if x%2==0]


[0, 4, 8, 12, 16]
# You can add more arguments:

>>> [x+y for x in [10,30,50] for y in [20,40,60]]


[30, 50, 70, 50, 70, 90, 70, 90, 110]
Tuples in Python
A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to
a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists
which are mutable.

# Creating non-empty tuples

# One way of creation


tup = 'python', 'geeks'
print(tup)

# Another for doing the same


tup = ('python', 'geeks')
print(tup)

Output

('python', 'geeks')

('python', 'geeks')

Note: In case you’re generating a tuple with a single element, make


sure to add a comma after the element.

Concatenation of Tuples
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')

# Concatenating above two


print(tuple1 + tuple2)
Output:

(0, 1, 2, 3, 'python', 'geek')


Nesting of Tuples
# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output :

((0, 1, 2, 3), ('python', 'geek'))

Repetition in Tuples
# Code to create a tuple with repetition

tuple3 = ('python',)*3
print(tuple3)
Output

('python', 'python', 'python')

Try the above without a comma and check. You will get tuple3 as a string
‘pythonpythonpython’.

Immutable Tuples

#code to test that tuples are immutable


tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Output

Traceback (most recent call last):

File "e0eaddff843a8695575daec34506f126.py", line 3, in

tuple1[0]=4
TypeError: 'tuple' object does not support item assignment

Slicing in Tuples
# code to test slicing

tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Run on IDE
Output

(1, 2, 3)

(3, 2, 1, 0)

(2, 3)

Deleting a Tuple
# Code for deleting a tuple

tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Run on IDE
Error:

Traceback (most recent call last):

File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>

print(tuple3)

NameError: name 'tuple3' is not defined

Output:
(0, 1)

Finding Length of a Tuple


# Code for printing the length of a tuple

tuple2 = ('python', 'geek')


print(len(tuple2))
Run on IDE
Output

Converting list to a Tuple


# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'
Run on IDE
Output

(0, 1, 2)

('p', 'y', 't', 'h', 'o', 'n')

Takes a single parameter which may be a list,string,set or even a dictionary( only keys
are taken as elements) and converts them to a tuple.

Tuples in a loop
#python code for creating tuples in a loop

tup = ('geek',)
n = 5 #Number of time loop runs
for i in range(int(n)):
tup = (tup,)
print(tup)
Output :

(('geek',),)

((('geek',),),)

(((('geek',),),),)

((((('geek',),),),),)

(((((('geek',),),),),),)

Using cmp(), max() , min()


# A python program to demonstrate the use of
# cmp(), max(), min()

tuple1 = ('python', 'geek')


tuple2 = ('coder', 1)

if (cmp(tuple1, tuple2) != 0):

# cmp() returns 0 if matched, 1 when not tuple1


# is longer and -1 when tuple1 is shoter
print('Not the same')
else:
print('Same')
print ('Maximum element in tuples 1,2: ' +
str(max(tuple1)) + ',' +
str(max(tuple2)))
print ('Minimum element in tuples 1,2: ' +
str(min(tuple1)) + ',' + str(min(tuple2)))

Output
Not the same

Maximum element in tuples 1,2: python,coder

Minimum element in tuples 1,2: geek,1

Note: max() and min() checks the based on ASCII values. If there are two strings in a tuple,
then the first different character in the strings are checked.

Python Tuple Methods


Methods that add items or remove items are not available with tuple. Only the following
two methods are available.

my_tuple = ('a','p','p','l','e',)
Python Tuple Method

# Count
# Output: 2
Method Description print(my_tuple.count('p'))

# Index
count(x) Return the number of items that is equal to x
# Output: 3
print(my_tuple.index('l'))
index(x) Return index of first item that is equal to x

Print how many time ‘o’ is repeated in a given string?(“hello,how are you?”)

a="Hello How are you?"


l=tuple(a)
print l
print l.count('o')

Você também pode gostar