python: IndexError: tuple index out of range - python

I cannot seem to understand why my code is displaying this error.
IndexError: tuple index out of range
Code:
l = ['Simpson', ',', 'Bartholomew', 'Homer', 'G400', 'Year', '2']
x = '{}'* len(l)
print(x)
x.format(l)
print(x)

Maybe you were looking for an unpacking:
>>> x.format(*l)
'Simpson,BartholomewHomerG400Year2'

You are passing in just one argument, the list l, while your format string expects there to be 7 arguments.
If you wanted each element in l to be formatted, then use the *arg call syntax:
x.format(*l)
You want to print the return value, though:
result = x.format(*l)
print(result)
Demo:
>>> print(x.format(*l))
Simpson,BartholomewHomerG400Year2

Related

Tuple fails to print index if the item is repeated more than once

I am learning Python3 and I'm in tuples chapter now.
While we can use index method to print the place of an item like this:
>>> tup = ('a','b','a','c')
>>> tup.index('c')
>>> 3
But when I try to print the index for repeated item, it only prints for the first item and simply ignore the second one.
>>> tup.index('a')
0
I am expecting tuple to print both index (location).
Expected output
>>> tup.index('a')
0, 2
May I know why tuple having this behaviour? what if if we want to print the index for the repeated item in the tuple?
tuple.index is actually a three-argument function: tuple.index(x, start, end). It finds the first element equal to x in the range tuple[start:end]. It's just that by default start = 0 and end = len(t).
If you want the index of the second element you can do:
>>> i = tup.index('a')
>>> tup.index('a', i + 1)
2
If you want all indices you can use a list comprehension like L3viathan suggests.
Because that's what tuple.index does:
>>> help(tup.index)
index(...)
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
If you want all indices, you can make a list comprehension:
indices = [i for i, val in enumerate(tup) if val == 'c']
You can also do this with numpy.argwhere
https://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html
import numpy as np
np.argwhere(tup == 'a')

Reverse a list of string giving me none [duplicate]

This question already has answers here:
How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
(11 answers)
Closed 5 years ago.
s is a string and following code is giving me "None" while executing
n=list(s)
l = n.reverse()
print(l)
Try this:
n=list(s)
n.reverse()
print(n)
reverse
You got to copy the list and then reverse it with l.reverse(), not l = n.reverse().
copy
You have to use copy, not just l = n, because if you do so you will have two reference to the same data, so that when you reverse l you reverse also n. If you do not want to reverse also the original n list, you have to make a brand new copy with l = n. copy, then you reverse l, without modifying the original data stored with n label. You can copy a list also with l = n[:].
>>> s = "12345"
>>> n = list(s)
>>> l = n.copy() # or l = n[:]
>>> l.reverse()
>>> n
['1', '2', '3', '4', '5']
>>> l
['5', '4', '3', '2', '1']
>>>
Thake a list and get the items in a string
If you want a string back
>>> k = "".join(l)
>>> k
'54321'
Problem:
reverse() function is doing in place reversal of list and it is not returning anything that's the reason l gets assigned None
As a solution after calling reverse() print variable n itself as shown
s = "abc"
n=list(s)
n.reverse()
print(n)
For your code, it should be
s='string'
n=list(s)
n.reverse()
print(''.join(n))
Output:
gnirts
You can use [::-1] for reverse.Slice notation is easy to reverse string
s = "reverse"
s = s[::-1]
print(s)
output
esrever
reverse() function returns None but reverse the list.
n=list(s)
l = n.reverse()
print(l)
print(n) #Reversed list
You can use reversed() function as well.
l = list(reversed(n))
print(l)

Convert list to string using python

I have the list it contain int ,float and string:
lists = [10, "test", 10.5]
How Can i convert above list to string? I have tried:
val = ','.join(lists)
print val
I am getting error like this:
sequence item 0: expected string, int found
How can I solve this issue?
Firstly convert integers to string using strusing map function then use join function-
>>> ','.join(map(str,[10,"test",10.5]) )#since added comma inside the single quote output will be comma(,) separated
>>> '10,test,10.5'
Or if you want to convert each element of list into string then try-
>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']
Or use itertools for memory efficiency(large data)
>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']
Or simply use list comprehension
>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']
The easiest way is to send the whole thing to str() or repr():
>>> lists = [10, "test", 10.5]
>>> str(lists)
"[10, 'test', 10.5]"
repr() may produce a different result from str() depending on what's defined for each type of object in the list. The point of repr() is that you can send such strings back to eval() or ast.literal_eval() to get the original object back:
>>> import ast
>>> lists = [10, "test", 10.5]
>>> ast.literal_eval(repr(lists))
[10, 'test', 10.5]
a = ['b','c','d']
strng = ''
for i in a:
strng +=str(i)
print strng
The error you are getting because join wants elements to be string type, but in your list there is integer too, so 1st you have to convert them to type string.
you can use list comprehension and str and join to join them
>>> lists = [10,"test",10.5]
>>> ",".join(str(x) for x in lists)
You have to pass each item in your list as a string into the ','.join(sequence). Consider using:
val = ','.join([str(item) for item in lists])
print val
If you want to convert each element in the list to a string, you could do it simply using a for-loop.
for i in range(len(lists)):
lists[i] = str(lists[i])
Alternatively, if you want to make one string where all elements are joined together, you could edit the code above slightly.
string_of_lists = ""
for i in lists:
string_of_lists += str(i)
As you can tell, this is another way of doing it, apart from the other solutions using join.
I hope I helped!
This is also possible. Here x variable is list.
>>> '%s'*len(x) % tuple(x)
As mentioned here
list=['a/b/c', 'd/e/f']
file_list_string= ' '.join(list)
file_list_string= ' '.join(str(file) for file in list)
import functools
lists = [10,"test",10.5]
print(functools.reduce(lambda x,y:x+","+y,list(map(str,lists))))
You could always do it the dirty way:
list_name = ["a", "b", "c"];
string_name = "";
for c in list_name:
string_name += c
print(string_name)
OUTPUT:
"abc"
That should work with ints, floats, and strings, always converting them to string type.

How to write a function into a for loop

How would one answer this foor loop question using proper python syntax:
def int_all_2(str_list):
'''(list of str) -> NoneType
Replace every str element of str_list with its corresponding
int version.
For example,
>>> sl = ['100', '222', '2', '34']
>>> int_all_2(sl)
>>> sl
[100, 222, 2, 34]
'''
Would it be like this?
l = []
for x in str_list:
l.append (int_all_2(x))
return l
If you want to convert each element of the list to integer and then return a new list you can use map function :
def strs2ints(l):
return map(int,l)
You should also note that function strs2ints doesn't change the contents of array l.
In case you want to change the contents of the original array l, which I do not recommend(you should prefer using "clean" functions over functions with side-effects) you can try the following code :
def strs2ints(l):
for i in range(len(l)):
l[i] = int(l[i])
Assuming your list contains only string representation of numeric integers, you don't even need a function, just list comprehension:
l = [int(itm) for itm in str_list]
If you want to ignore possible strings:
l = [int(itm) for itm in str_list if not itm.isalpha]
Or, if you require a function:
def int_all(str_list):
return [int(itm) for itm in str_list]

iterating over two lists to create a new list in Python

I'm trying to iterate over two lists to populate a new list with the outcome, but am not sure where it's going wrong. Note: i'm a beginner using Python. Mahalo in advance!
sumList = [27400.0, 32900.0, 42200.0, 40600.0];
volList = [27000.0, 40000.0, 31000.0, 40000.0];
rendeList = [];
x = 0;
for sumValue in range (0, len(sumList)-1):
rendeList = rendeList.append((sumList[x]/volList[x])*100)
x += 1;
However, I get an Attribute Error: 'NoneType' object has no attribute 'append'. After running the for loop, i get:
print rendeList
None
My expected outcome would have been:
print rendeList
[101.48, 82.25, 136.13, 101.49]
list.append(x) modifies the list and returns None.
Change your code to:
for sumValue in range (0, len(sumList)):
rendeList.append((sumList[x]/volList[x])*100)
x += 1
Or simplify it to:
for sumValue, volValue in zip(sumList, volList):
rendeList.append((sumValue / volValue) * 100)
Here is your solution using list comprehension:
result = [a[0]/a[1]*100 for a in zip(sumList, volList)]
The root of your problem is that list.append returns None
>>> a_list = list('abc')
>>> print(a_list.append('d'))
None
>>> a_list
['a', 'b', 'c', 'd']
And if you reassign a_list:
>>> a_list = a_list.append('e')
>>> a_list
>>> print(a_list)
None
Python's map function would be perfect for this:
rendeList = map(lambda x,y: x/y*100, sumList, volList)
The map function returns a list where a function (the first argument, which here I've supplied as a Lambda expression) is applied to each element of the passed in list, or in this case each pair of elements from the two lists passed in.

Categories

Resources