Python: square brackets | Sololearn: Learn to code for FREE!


Python: square brackets

I'm comparing two chunks of code: aaa = ["abcdef"] bbb = ["ghijklmnop"] print (aaa[0][0:4]+bbb[0][3:7]) ### outputs abcdjklm aaa = ["abcdef"] bbb = ["ghijklmnop"] print (aaa[0:4]+bbb[3:7]) ### outputs ['abcdef'] Why does the second chunk of code not include letters from list bbb? What do the first sets of square brackets tell us? ie. aaa[ ] [ ] + bbb[ ][ ] ^ ^ ^ ^ ^ ^

9/11/2020 10:34:55 PM


2 Answers

New Answer


Those first square brackets tells us the first element in list aaa[0:4] means slice elements in list from index 0 upto index4-1 and return them but aaa only includes one element i.e. "abcdef" Second square bracket will slice from the string


a[0][0:4] means list a's 0th value which is "ab def" now for this slicing [0:4] return 0 to 3 charecters from it those are "abcd" Similarly b[0][3:7] return jklm In 2nd code a[0:4] means slice list values from 0 to index 3 but you have value at index 0 only, other returns empty so total value at index 0 returned and similarly b has also value at index 0 only , so slicing 3:7 to returns empty list.. So finally it only "a cdef" [0] is value at index position 0, [0:4] is slicing values from 0 index to 3. (4-1).