Python: Convert a list into a normal value - python

I have a list
a = [3]
print a
[3]
I want ot convert it into a normal integer
print a
3
How do I do that?

a = a[0]
print a
3
Or are you looking for sum?
>>> a=[1]
>>> sum(a)
1
>>> a=[1,2,3]
>>> sum(a)
6

The problem is not clear. If a has only one element, you can get it by:
a = a[0]
If it has more than one, then you need to specify how to get a number from more than one.

I imagine there are many ways.
If you want an int() you should cast it on each item in the list:
>>> a = [3,2,'1']
>>> while a: print int(a.pop())
1
2
3
That would also empty a and pop() off each back handle cases where they are strings.
You could also keep a untouched and just iterate over the items:
>>> a = [3,2,'1']
>>> for item in a: print int(item)
3
2
1

To unpack a list you can use '*':
>>> a = [1, 4, 'f']
>>> print(*a)
1 4 f

Related

How to select certain indices from a list? (i.e. the 1st, 6th and 13th value)

I have an enumerate for loop inside another enumerate loop and I want to use certain items from the inner list. I thought the following:
list1 = ['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']
for number, list in enumerate(list1):
for num, item in enumerate(list[0, 1, 4]):
print item
would print out:
a
b
e
one
two
five
1
2
5
But instead I get the error TypeError: list indices must be integers, not tuple. I know I can select a range using list1[0:5] for example so I assumed I could explicitly select items as well.
Can anyone explain how to achieve this print out?
If you know the indexes you want, you simply need to index said list at the specific indexes, and print the values.
You should also note however, that list are zero indexed. The first value is at index 0. That means you want 0, 1, 4, and not 1, 2, 5
>>> list1 = [['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']]
>>>
>>> for lst in list1:
a, b, c = lst[0], lst[1], lst[4]
print a
print b
print c
a
b
e
one
two
five
1
2
5
>>>
If you need a more general solution, you can iterate over the indexes you want to access, and print them out:
>>> def print_elements_at_indexs(indexes, lst):
for sublst in lst:
for index in indexes:
print(sublst[index])
>>> print_elements_at_indexs([0, 1, 4], list1)
a
b
e
one
two
five
1
2
5
>>>
Try this:
>>> list1 = [['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']]
>>> index1 = [1,2,5]
>>> [j for i in list1 for index,j in enumerate(i) if index+1 in index1]
['a', 'b', 'e', 'one', 'two', 'five', '1', '2', '5']
Check this
[v for _list in list1 for i,v in enumerate(_list) if i in [0,1,4]]
The error is in the second loop:
for num, item in enumerate(list[0, 1, 4]):
What you have written - list[1, 2, 5] was wrong in two accounts - list() is a reserved keyword you reassigned in the previous loop (not critical, but you shouldn't do it, period :), and you are passing a wrong slice construct - this is not the syntax how to select these 3 members. Plus, the indices are 0 based - the 1st element is 0, and so on.
Here's revised code based on your approach:
list1 = ['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']
for sub_list in list1:
for num in (0, 1, 4):
print sub_list[num]
No need to use enumerate(), as you're not using its index anyways.
list1 = [['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']]
for number, lst in enumerate(list1):
for num, item in enumerate(lst):
if num in [0,1,4]:
print item
Note : try avoiding built-in keyword as variable in your program.

Check if there's an item inside a list and if True modify it

list1 = [1,2,3]
def ex(example_list):
for number in example_list:
if(number == 2):
number = 3
ex(list1)
print(list1)
I need to check if there is the number 2 inside of the list1 and if it's inside of it, I want to modify it to 3.
But if I run the command, number would be 3, but list1 would remain [1,2,3] and not [1,3,3]
You can use enumerate() to get the index of the number you need to change:
list1 = [1,2,3]
def ex(example_list):
for idx, number in enumerate(example_list):
if(number == 2):
example_list[idx] = 3
ex(list1)
print(list1)
The variable number is an object with its own reference and not a reference to the item in the list.
The logic for checking and replacing can be done altogether in a list comprehension using a ternary operator since you're not actually using the index:
list2 = [3 if num==2 else num for num in list1]
References:
List comprehensions
Conditional expressions
In order to modify a list item, you need to know which slot it is in. The .index() method of lists can tell you.
list1 = [1,2,3]
i = list1.index(2)
list1[i] = 2
Now what happens if the list does not contain 2? index() will throw an exception, which normally will terminate your program. You can catch that error, however, and do nothing:
list1 = [1,2,3]
try:
i = list1.index(2)
except ValueError:
pass
else: # no error occurred
list1[i] = 2
So... The problem you're having is that, since number contains a basic type (an int), modifying number doesn't modify the reference inside the list. Basically, you need to change the item within the list by using the index of the item to change:
list1 = [1,2,3]
def ex(example_list):
for i, number in enumerate(example_list):
if(number == 2):
example_list[i] = 3 # <-- This is the important part
ex(list1)
print(list1)
Of just using the index (might be clearer):
list1 = [1,2,3]
def ex(example_list):
for i in range(len(example_list)):
if(example_list[i] == 2):
example_list[i] = 3
ex(list1)
print(list1)
l.index(n) will return the index at which n can be found in list l or throw a ValueError if it's not in there.
This is useful if you want to replace the first instance of n with something, as seen below:
>>> l = [1,2,3,4]
>>> # Don't get to try in case this fails!
>>> l[l.index(2)] = 3
>>> l
[1, 3, 3, 4]
If you need to replace all 2's with 3's, just iterate through, adding elements. If the element isn't 2, it's fine. Otherwise, make it 3.
l = [e if e != 2 else 3 for e in l]
Usage:
>>> l = [1,2,3,4]
>>> l = [e if e != 2 else 3 for e in l]
>>> l
[1, 3, 3, 4]

How to Append The Calculated Arithmetic to The List?

Let say we have this simple arithmetic:
y = 1 + 1
Can I append the result of the arithmetic to a list directly like so:
num_list = []
l = num_list.append(y)
I have tried to print the list to see if the result has been appended to the list, but I noticed it gives me "None" as output. Any idea how to approach this?
you should not print l, you should print num_list to see the appended list. Here is the sample test in python command line
>>> y = 1 + 1
>>> list1 = []
>>> list1.append(y)
>>> print list1
[2]
>>> print l
None
>>>

Python check if an item is in a list

Sorry, I'm very much a beginner to python. What I want to do is see which list an item is in. What I have is some lists set up like:
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
And let's say I want to find which list the item 5 is in.
What I'm currently doing is:
if l1.index(5)!=False:
print 1
elif l2.index(5)!=False:
print 2
elif l3.index(5)!=False:
print 3
But this doesn't work. How would I do this?
You can use in operator to check for membership:
>>> 5 in [1, 3, 4]
False
>>> 5 in [1, 3, 5]
True
In addition to the answer with the "in" operator, you should do that with a loop by inserting all the list to one list and then send it to a function and loop over it. Note that the first 'in' belongs to the for loop and the second 'in' is the operator:
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
all_lst = [l1,l2,l3]
list_contain_num(all_lst)
def list_contain_num(all_lst):
for lst in all_lst:
if 5 in lst:
print('the containing list is: ' + str(lst) )
if l1.index(5)!=False:
print 1
The index() method does not return True or False, it returns the index. So you would change this to:
if l1.index(5) >= 0:
print 1

Changing up the contents of a list

If i have a list of integers such as [1,2,3]
How would I remove the [ and , to make it just 1 2 3 with spaces
I tried converting it to a string and using the split method but I don't know how to convert back into a integer and print it out. I have this:
z = map(str,x.split(" ,"))
but like I said i don't know how to make that a integer again and print it out.
I tried:
t = map(int,z)
and that did not work.
>>>x = [1,2,3]
1 2 3
For convert to string with space you need to convert all the entries to str with map(str,l) and join them with ' '.join , the for reverse to list first you need to split the string with str.split() and then convert to int with map :
>>> l=[1,2,3]
>>> ' '.join(map(str,l))
'1 2 3'
>>> string=' '.join(map(string,l))
>>> map(int,string.split())
[1, 2, 3]
Your question doesn't really make sense. the [, ,, and ] are what DEFINE it as a list. Those markings are simply the way that Python shows it is a list. If you want to DISPLAY it as something other than a list, you probably want str.join. However that requires that each element in the list be a string, so you're left with either:
>>> some_list = [1,2,3]
>>> print(some_list)
[1, 2, 3]
>>> print(" ".join(map(str, some_list)))
1 2 3
or:
>>> print(" ".join([str(el) for el in some_list]))
1 2 3
' '.join(str(i) for i in my_list)

Categories