tuple and list in python
#to create a tuple you use ( ) :
myTuple = ()
#but to create a list you use [ ] :
myList = []
#tuples cannot be changed while the lists can be modified but Tuples are
#more memory efficient
#Code_Breaker
tuple and list in python
#to create a tuple you use ( ) :
myTuple = ()
#but to create a list you use [ ] :
myList = []
#tuples cannot be changed while the lists can be modified but Tuples are
#more memory efficient
#Code_Breaker
python list of tuples
#List of Tuples
list_tuples = [('Nagendra',18),('Nitesh',28),('Sathya',29)]
#To print the list of tuples using for loop you can print by unpacking them
for name,age in list_tuples:
print(name,age)
#To print with enumerate--->enumerate is nothing but gives the index of the array.
for index,(name,age) in list_tuples:
#print using fstring
print(f'My name is {name} and age is {age} and index is {index}')
#print using .format
print('My name is {n} and age is {a} and index is {i}'.format(n=name,a=age,i=index))
tuples in python
t = 12345, 54321, 'hello!'
print(t[0])
# output 12345
print(t)
# output (12345, 54321, 'hello!')
# Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
print(u)
# output ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# Tuples are immutable:
# assigning value of 12345 to 88888
t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
print(v)
# output ([1, 2, 3], [3, 2, 1])
list of tuples python
import string
fhand = open('romeo-full.txt')
counts = dict()
for line in fhand:
line = line.translate(None, string.punctuation)
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
# Sort the dictionary by value
lst = list()
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse=True)
for key, val in lst[:10] :
print key, val
tuples in python
strs = ['ccc', 'aaaa', 'd', 'bb'] print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa']
#the list will be sorted by the length of each argument
tuple and list in python
#to create a tuple you use ( ) :
myTuple = ()
#but to create a list you use [ ] :
myList = []
#tuples cannot be changed while the lists can be modified but Tuples are
#more memory efficient
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us