I'm fairly new to python and I'm currently working on a program that will encrypt and decrypt strings. As part of it, I need the individual letters of the string to each be added to an empty list; for example, the string 'hello' would be entered into a list list like so:
['h','e','l','l','o']
The part of the code that is giving me this error can be found below. Thanks.
emptyList=[]
message=input("What Would You Like To Encrypt?\n")
messageLength=len(message)
for count in range(0,messageLength):
emptyList=[]
emptyList[count].append(message[count])
You are trying to address indices in an empty list:
>>> lst = []
>>> lst[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> lst[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
If you wanted to add elements to a list, just use list.append() directly on the list object itself to create more indices; don't create new empty lists each time:
emptyList=[]
messageLength=len(message)
for count in range(0,messageLength):
emptyList.append(message[count])
Not that you need to be this elaborate, the following is enough:
emptyList = list(message)
list() takes any iterable and adds all the elements of that iterable to a list. Since a string is iterable, producing all the characters in that string, calling list() on a string creates a list of those characters:
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Basically you want just read from the input and then output a list
Python 2.7
message=raw_input("What Would You Like To Encrypt?\n")
print list(message)
Python 3.X
message=input("What Would You Like To Encrypt?\n")
print(list(message))
Output
If you input Hello
['H', 'e', 'l', 'l', 'o']
Related
This question already has answers here:
What's the difference between lists and tuples?
(22 answers)
Closed 21 days ago.
I am trying to understand the difference between tuples and lists
I was trying to use tuples and lists in a piece of my code, and not realising the difference between tuple and list, could someone please tell me difference,
Thanks,
Gops
Both list and tuple are used to store multiple items within a single collection, but there is a key difference tuple is immutable while list is not. Mutability means the ability to modify the object afterward.
# Here we can modify my_list just fine
>>> my_list = ["hello"]
>>> my_list[0] = "world"
>>> print(my_list)
['world']
# But modifying my_tuple leads to an error
>>> my_tuple = ('hello',)
>>> my_tuple[0] = 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> print(my_tuple)
('h', 'e', 'l', 'l', 'o')
You might think to ask why use tuples at all if we can't mutate them. Wouldn't it be better to just have everything be more flexible?
Well, there are things that tuples can do that lists cannot do such as acting as keys for a dictionary. This is a very useful trick for things like points as keys.
>>> my_dict = {("hello", "world"): "foo"}
>>> my_dict[("hello", "world")]
'foo'
If you try to do the same with lists, you get this error. The error message hints at the key difference. Lists cannot be hashed but tuples can be hashed.
>>> my_dict = {["hello", "world"]: "foo"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
This question already has answers here:
Why does += behave unexpectedly on lists?
(9 answers)
Closed 2 years ago.
>>> r = [[]]
>>> r[0] = r[0] + 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> r[0] += 'abc'
>>> r
[['a', 'b', 'c']]
Could somebody explain why second assignment works but not the first one ?
Why += works and + doesn't work is "that's how its coded". But I haven't figured out any good reason for it. Lets focus simply on list addition
operator magic method list equiv
-------- ------------ ----------
+= (inplace add) __iadd__ list_inplace_concat
+ (add) __add__ list_concat
Inplace Add / list_inplace_concat works on any sequence. Under the covers, python simply calls list.extend which turns the right hand side into an iterator and so works with all sequences
>>> test = []
>>> test += 'abc'
>>> test
['a', 'b', 'c']
Add / list_concat is hardcoded to work only with other lists. The underlying C code uses the internal data structure of the list to copy its elements.
>>> test + 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
Change the right hand side to a list and it works
>>> test + list('abc')
['a', 'b', 'c', 'a', 'b', 'c']
>>>
list_concat is optimized to use the size of the two lists to know exactly how large the new list needs to be. Then it does member copy at the C structure level. What puzzles me is why there isn't a fallback when the "not a list" condition is detected. The list could be copied and extended.
Trying to run this code :
sorted_by_name = sorted(sort_array,key=lambda x:x[0]))
I get:
IndexError: list index out of range
How do I resolve this?
Thanks
Well one of element in the sort_array should be either empty or null string. See the below examples
Example #1:
sort_array = ['abc', 'acd', 'abcd', '']
sort_array
['abc', 'acd', 'abcd', '']
sorted(sort_array, key=lambda student: student[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
IndexError: string index out of range
For example #2, i will take sort_array as list of lists, which matches more to your example of sorted_by_name
>>> student_tuples = [
... ['john', 'A', 15],
... []
... ]
>>> sorted_by_name = sorted(student_tuples,key=lambda x:x[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
IndexError: list index out of range
Hence I request you to please check your input sort_array once, if it has any empty lists
That means that at least one thing in your list is empty so doesn't have a first element. The fix is simple, don't pass a key:
sorted_by_name = sorted(sort_array)
The default implementation of sorted already tries the first item, then the second item, the third item, etc. When you pass it a key, it first tries your key, the first item. If it finds that two are the same, it does its own check. It checks the first item (again), the second item, the third item, etc. In other words, both are the same except that supplying a key might mean that the first item is checked twice, and of course the default implementation doesn't error on an empty list.
I would like to convert a list of following strings into integers:
>>> tokens
['2', '6']
>>> int(tokens)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'list'
Other than writing a for loop to convert each member of the list tokens, is there a better way to do that? Thanks!
Just use list comprehension:
[int(t) for t in tokens]
Alternatively map the int over the list
map(int, tokens)
However map is changed in python3, so it creates an instance of the map and you would have to cast that back into a list if you want the list.
i = iter(list)
while i.next != None:
print int(i.next())
Hello my fellow programmers.
I am a fairly new programmer, and now I am facing a great predicament. I am getting the error:
can only assign an iterable
Firstly I don't know what that means.
Secondly I will leave my code for you professionals to critique it:
def num_top(int_lis):
duplic_int_lis = int_lis
int_firs= duplic_int_lis [0]
int_lis[:] = duplic_int_lis [int_firs]
Basically I am trying to find the [0] element in the list and then using that int as an index position to find the integer at that index position.
int_lis[:] = duplic_int_lis [int_firs] means assign all the items of duplic_int_lis [int_firs] to int_lis, so it expects you to pass an iterable/iterator on the RHS.
But in your case you're passing it an non-iterable, which is incorrect:
>>> lis = range(10)
>>> lis[:] = range(5)
>>> lis #all items of `lis` replaced with range(5)
[0, 1, 2, 3, 4]
>>> lis[:] = 5 #Non-iterable will raise an error.
Traceback (most recent call last):
File "<ipython-input-77-0704f8a4410d>", line 1, in <module>
lis[:] = 5
TypeError: can only assign an iterable
>>> lis[:] = 'foobar' #works for any iterable/iterator
>>> lis
['f', 'o', 'o', 'b', 'a', 'r']
As you cannot iterate over an integer, hence the error.
>>> for x in 1: pass
Traceback (most recent call last):
File "<ipython-input-84-416802313c58>", line 1, in <module>
for x in 1:pass
TypeError: 'int' object is not iterable
The RHS of a slice-assignment must be an iterable, not a scalar. Consider slice-deleting and then appending instead.
An iterable is a thing with multiple items that you can iterate through (for example: take the 1st value do something, then the 2nd do something, etc...) Lists, dictionaries, tuples, strings have several items in them and can be used as iterables. As a counterexample: number types don't qualify as iterable.
Remember that computers count from #0 so: if you want the first value of a list you can use
my_list[0]
before you go further I would suggest watching this video about looping. https://www.youtube.com/watch?v=EnSu9hHGq5o