bugbytes
bugbytes

Reputation: 335

Subtracting from len([list]) python

I am new in python and wondering for list

a= [blabla, lala, haha, test]

can i do a subtraction like

b= 10- len([a])

if not whats the way to do subtract from the number of elements in a list?

Upvotes: 0

Views: 5712

Answers (4)

Stephan
Stephan

Reputation: 17981

It sounds like you want to shorten the list. You said you wanted to subtract from the number of elements in the list

b = a[:-10]

will delete the last 10 elements and store them in b, a will remain the same

edit I might be misunderstanding your english

Also, 10 - len([a]) will always be 9 because [a] is a list of size 1 and 10-1=9, len(a) will tell you how long a is.

Upvotes: 0

arshajii
arshajii

Reputation: 129507

[a] is a new list containing only a, so its length is always 1, meaning b will always be 10 - 1 == 9.

You likely meant

b = 10 - len(a)

See len()

Upvotes: 1

jh314
jh314

Reputation: 27792

You should change this:

b = 10 - len([a])

to this:

b = 10 - len(a)

The issue with b = 10 - len([a]) is that [a] will be a list with a single element, namely the list a (which is ['blabla', 'lala', 'haha', 'test']).

len(a) should give you the length of the list a.

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

I guess this is what you mean:

a = ['blabla', 'lala', 'haha', 'test']
b = 10 - len(a)

b
=> 6 # 10 - 4 == 6

Yes, you can do that :-) . In your code this part won't work as you expect: len([a]) because that's finding the length of a list with the single element a, which also happens to be a list - and it will always evaluate to 1.

Upvotes: 1

Related Questions