-1

I have a list and I a trying to concatenate 2 items in the list using .join().

Sample data:

l = ['a', 'b', 'c', 'd']
str = ' '.join(l[1:2])
print(str)

The output prints only b but I am expecting to print b c. someone point me what is wrong here

Worm
  • 1,313
  • 2
  • 11
  • 28
shan
  • 467
  • 4
  • 9
  • 20
  • `l[1:2]` starts at index 1 but end _before_ index 2, so it only has 1 item in it, `'b'`. So you want `' '.join(l[1:3])` – PM 2Ring Jul 16 '18 at 19:44
  • 1
    indexing goes `[start:exclusive end]`, if you index `[1:2]` you are going from `1` to `2` exclusive, so just the element at index `1`, which is b – Sam Jul 16 '18 at 19:44
  • 1
    BTW, don't use `str` as a variable name: that shadows the built-in `str` type, which can lead to mysterious error messages if you later try to do stuff like `str(42)`. – PM 2Ring Jul 16 '18 at 19:46
  • @PM2Ring: I was searching for concatenation in list and the duplicate question which U have mentioned dint come up in my search results.It is not like I am vaguely asking someone to explain a concept. I tried an method and it dint workout so asking for help. – shan Jul 17 '18 at 06:08
  • That's ok. It can be hard to find the right question when you don't understand what's causing the problem. – PM 2Ring Jul 17 '18 at 06:16

2 Answers2

1

from the python docs, slicing of list as l[a:b] a is inclusive but b is exclusive, hence the desired results

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
1
l = ['a','b','c','d']
string = ' '.join(l[1:3])
print(string)

Your index is ending before 2, using [1:3] includes 2. You also had some syntax error in your list for c and d

EDIT: as others have stated I'd also recommend avoiding "str" use since str() is used in python to convert into a string.

J0hn
  • 570
  • 4
  • 19
  • 1
    `str` isn't a function, it's a class (also known as a type). Yes, you can call it, but that doesn't make it a function. – PM 2Ring Jul 16 '18 at 19:48